Spring Boot使用@Profile
注解可以实现不同环境下配置参数的切换,任何@Component
或@Configuration
注解的类都可以使用@Profile
注解。
例如:
@Configuration @Profile("production") public class ProductionConfiguration { // ... }
通常,一个项目中可能会有多个profile场景,例如下面为test场景:
@Configuration @Profile("test") public class TestConfiguration { // ... }
在存在多个profile情况下,你可以使用spring.profiles.active
来设置哪些profile被激活。spring.profiles.include
属性用来设置无条件的激活哪些profile。
例如,你可以在application.properties
中设置:
或者在application.yaml
中设置:
spring.profiles.active
属性可以通过命令行参数或者资源文件来设置,其查找顺序,请参考Spring Boot特性。
自定义Profile注解
@Profile
注解需要接受一个字符串,作为场景名。这样每个地方都需要记住这个字符串。Spring的@Profile
注解支持定义在其他注解之上,以创建自定义场景注解。
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Profile("dev") public @interface Dev { }
这样就创建了一个@Dev
注解,该注解可以标识bean使用于@Dev
这个场景。后续就不再需要使用@Profile("dev")
的方式。这样即可以简化代码,同时可以利用IDE的自动补全:)
多个Profile例子
下面是一个例子:
package com.javachen.example.service; public interface MessageService { String getMessage(); }
对于MessageService接口,我们可以有生产和测试两种实现:
package com.javachen.example.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile({ "dev" }) public class HelloWorldService implements MessageService{ @Value("${name:World}") private String name; public String getMessage() { return "Hello " + this.name; } }
package com.javachen.example.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; @Component @Profile({ "prod" }) public class GenericService implements MessageService { @Value("${hello:Hello}") private String hello; @Value("${name:World}") private String name; @Override public String getMessage() { return this.hello + " " + this.name; } }
Application类为:
@SpringBootApplication public class Application implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(Application.class); @Autowired private MessageService messageService; @Override public void run(String... args) { logger.info(this.messageService.getMessage()); if (args.length > 0 && args[0].equals("exitcode")) { throw new ExitException(); } } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
实际使用中,使用哪个profile由spring.profiles.active
控制,你在resources/application.properties
中定义spring.profiles.active=XXX
,或者通过-Dspring.profiles.active=XXX
。XXX
可以是dev
或者prod
或者dev,prod
。需要注意的是
:本例中是将@Profile
用在Service类上,一个Service接口不能同时存在超过两个实现类,故本例中不能同时使用dev和prod。
通过不同的profile,可以有对应的资源文件application-{profile}.properties
。例如,application-dev.properties
内容如下:
name=JavaChen-dev
application-prod.properties
内容如下:
接下来进行测试。spring.profiles.active=dev
时,运行Application类,查看日志输出。
2016-02-22 15:45:18,470 [main] INFO com.javachen.example.Application - Hello JavaChen-dev
spring.profiles.active=prod
时,运行Application类,查看日志输出。
2016-02-22 15:47:21,270 [main] INFO com.javachen.example.Application - Hello JavaChen-prod
logback配置多Profile
在resources目录下添加logback-spring.xml,并分别对dev和prod进行配置:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!--<include resource="org/springframework/boot/logging/logback/base.xml" />--> <springProfile name="dev"> <logger name="com.javachen.example" level="TRACE" /> <appender name="LOGFILE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> </springProfile> <springProfile name="prod"> <appender name="LOGFILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <File>log/server.log</File> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>log/server_%d{yyyy-MM-dd}.log.zip</FileNamePattern> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%date [%thread] %-5level %logger{80} - %msg%n</pattern> </layout> </appender> </springProfile> <root level="info"> <appender-ref ref="LOGFILE" /> </root> <logger name="com.javachen.example" level="DEBUG" /> </configuration>
这样,就可以做到不同profile场景下的日志输出不一样。
maven中的场景配置
使用maven的resource filter可以实现多场景切换。
<profiles> <profile> <id>prod</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <build.profile.id>prod</build.profile.id> </properties> </profile> <profile> <id>dev</id> <properties> <build.profile.id>dev</build.profile.id> </properties> </profile> </profiles> <build> <filters> <filter>application-${build.profile.id}.properties</filter> </filters> <resources> <resource> <filtering>true</filtering> <directory>src/main/resources</directory> </resource> </resources> </build>
这样在maven编译时,可以通过-P
参数指定maven profile即可。
总结
使用Spring Boot的Profile注解可以实现多场景下的配置切换,方便开发中进行测试和部署生产环境。
本文中相关代码在github上面。
相关推荐
1.2.2 使用Spring Initializr初始化Spring Boot项目 10 1.3 小结 18 第2章 开发第一个应用程序 19 2.1 运用Spring Boot 19 2.1.1 查看初始化的Spring Boot新项目 21 2.1.2 Spring Boot项目构建过程解析 ...
1.2.2 使用Spring Initializr初始化Spring Boot项目 10 1.3 小结 18 第2章 开发第一个应用程序 19 2.1 运用Spring Boot 19 2.1.1 查看初始化的Spring Boot新项目 21 2.1.2 Spring Boot项目构建过程...
本教程为笔者学习 Spring Boot 时写的笔记,适合没有接触过此框架的新手。内容非常全面,其中的代码都能运行,笔者都做了验证。本教程是简单笔记记录,从零到一学习 Spring Boot。本教程涉及的知识如下: Hell World...
Spring Boot Documentation 1. About the Documentation 2. Getting Help 3. First Steps 4. Working with Spring Boot 5. Learning about Spring Boot Features 6. Moving to Production 7. Advanced Topics II. ...
如果使用Spring Boot 1,请参阅。 注意:此工件名称在已更改。 旧名称是“ spring-boot-ext-logback-access”。产品特点自动检测您的配置文件并配置Logback访问。 支持类路径上的配置文件。 支持X-Forwarded-* HTTP...
1.6 使用Spring Initializer向导快速创建Spring Boot 16 2 Spring Boot配置 18 2.1 配置文件 18 2.2 YML语法 19 2.3 YML配置文件值获取 21 2.4 properties配置文件乱码问题 24 2.5 @ConfigurationProperties与@Value...
JavaEE开发的颠覆者 Spring Boot实战,多个地址免费下载,第一部分 点睛Spring 4.x 第1 章 Spring 基础 ..........................................2 1.1 Spring 概述 ................................................
示例代码相关文章Spring Boot 配置 TomcatSpring Boot 配置 profileSpring Boot 整合 DevTools(实现热部署)spring-boot-devtoolsSpring Boot 整合 Web 开发spring-boot-webSpring Boot 整合 Thymeleafspring-boot-...
spring boot 项目代码,直接启动,第一部分 点睛Spring 4.x 第1 章 Spring 基础 ..........................................2 1.1 Spring 概述 ............................................. 2 1.2 Spring 项目...
涵盖使用Spring Boot 进行Java EE 开发的绝大数应用场景,包含:Web 开发、数据访问、安全控制、批处理、异步消息、系统集成、开发与部署、应用监控、分布式系统开发等。 第一部分 点睛Spring 4.x 第1 章 Spring ...
spring-boot-groovy-config 使用Groovy文件配置Spring Boot应用程序。 这不仅允许以时髦的DSL方式指定属性,而且还允许(小的)逻辑并在配置内部重复使用(请注意,配置中的复杂逻辑通常不是一个好主意,但是在某些...
Spring.Boot.in.Action.2015.12.pdfFor online information and ordering of this and other manning books, please visit www.manning.com.thepublisheroffersdiscountsonthisbookwhenorderedinquantity For more ...
本篇文章主要介绍了Spring Boot的Profile配置详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
在Spring Boot中,可以使用配置文件来管理应用程序的配置。这些配置文件可以根据不同的环境进行分离和管理,Spring...Spring Boot还提供了更多高级的配置方式,如使用@Profile注解、条件注解等来实现更精细的配置管理。
主要介绍了使用Spring boot 的profile功能实现多环境配置自动切换的相关知识,非常不错,具有一定的参考借鉴价值 ,需要的朋友可以参考下
涵盖使用Spring Boot 进行Java EE 开发的绝大数应用场景,包含:Web 开发、数据访问、安全控制、批处理、异步消息、系统集成、开发与部署、应用监控、分布式系统开发等。 第一部分 点睛Spring 4.x 第1 章 Spring ...
avaEE开发的颠覆者 Spring Boot实战 完整版+书签+pdf+源码.rar JavaEE开发的颠覆者 Spring ..., 当你学完《JavaEE开发的颠覆者: Spring Boot实战》后,你将能使用Spring Boot 解决Java EE 开发中所遇到的绝大多数问题
Profile是Spring Boot 对不同环境下提供不同配置功能的支持
涵盖使用Spring Boot 进行Java EE 开发的绝大数应用场景,包含:Web 开发、数据访问、安全控制、批处理、异步消息、系统集成、开发与部署、应用监控、分布式系统开发等。 第一部分 点睛Spring 4.x 第1 章 Spring ...
,springboot支持通过不同的profile来配置不同环境的配置,下面就大致介绍一下yml配置文件跟properties配置文件怎么使用profile配置不同环境的配置文件