【转】Spring Boot Profile使用
http://blog.csdn.net/he90227/article/details/52981747
摘要: spring Boot使用@Profile注解可以实现不同环境下配置参数的切换,任何@Component或@Configuration注解的类都可以使用@Profile注解。 例如: @Configuration @Profile("production") public class Produc...
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中设置:
spring.profiles.active=dev,hsqldb
或者在application.yaml中设置:
spring.profiles.active:dev,hsqldb
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内容如下:
name=JavaChen-prod
接下来进行测试。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上面。
【转】Spring Boot Profile使用的更多相关文章
- 从.Net到Java学习第五篇——Spring Boot &&Profile &&Swagger2
从.Net到Java学习系列目录 刚学java不久,我有个疑问,为何用到的各种java开源jar包许多都是阿里巴巴的开源项目,为何几乎很少见百度和腾讯?不是说好的BAT吗? Spring Boot 的 ...
- Spring Boot - Profile配置
Profile是什么 Profile我也找不出合适的中文来定义,简单来说,Profile就是Spring Boot可以对不同环境或者指令来读取不同的配置文件. Profile使用 假如有开发.测试.生 ...
- Spring boot profile 多环境配置
1.多Profile文件 我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml 默认使用application.properties的配置 ...
- Spring Boot+Profile实现不同环境读取不同配置
文件结构如下: 但是官方推荐放在config文件夹下. 作用: 不同环境的配置设置一个配置文件,例如:dev环境下的配置配置在application-dev.properties中.prod环境下的配 ...
- Spring Boot系列之-profile
Spring Boot profile用于分离不同环境的参数配置,通过spring.profile.active参数设置使用指定的profile. 在Spring Boot中应用程序配置可以使用2种格 ...
- 吐血整理 20 道 Spring Boot 面试题,我经常拿来面试别人!
面试了一些人,简历上都说自己熟悉 Spring Boot, 或者说正在学习 Spring Boot,一问他们时,都只停留在简单的使用阶段,很多东西都不清楚,也让我对面试者大失所望. 下面,我给大家总结 ...
- Quick Guide to Microservices with Spring Boot 2.0, Eureka and Spring Cloud
https://piotrminkowski.wordpress.com/2018/04/26/quick-guide-to-microservices-with-spring-boot-2-0-eu ...
- 紧急整理了 20 道 Spring Boot 面试题,我经常拿来面试别人!
面试了一些人,简历上都说自己熟悉 Spring Boot, 或者说正在学习 Spring Boot,一问他们时,都只停留在简单的使用阶段,很多东西都不清楚,也让我对面试者大失所望. 下面,我给大家总结 ...
- 20 道 Spring Boot 面试题
转自:微信公众号:Java技术栈(id: javastack) 面试了一些人,简历上都说自己熟悉 Spring Boot, 或者说正在学习 Spring Boot,一问他们时,都只停留在简单的使用阶段 ...
随机推荐
- 1.文本编辑器-->CKEditor+CKFinder使用与配置
一.CKEditor介绍 官网地址:http://ckeditor.com CKEditor下载地址:http://ckeditor.com/download CKFinder(免费版本)下载地址:h ...
- Backbone之温故而知新1-MVC
在忙碌了一段时间之后,又有了空余时间来学习新的东西,自从上次研究了backbone之后,一直不得入门,今天有时间有温故了一次,有了些许进步在此记录下, 在开始之前,不得不提一下我的朋友给了我“豆瓣音乐 ...
- mysql-profiling详解
要想优化一条 Query,我们就需要清楚的知道这条 Query 的性能瓶颈到底在哪里,是消耗的 CPU计算太多,还是需要的的 IO 操作太多?要想能够清楚的了解这些信息,在 MySQL 5.0 和 M ...
- JS之捕获冒泡和事件委托
一.事件流(捕获,冒泡) 事件流:指从页面中接收事件的顺序,有冒泡流和捕获流. 当页面中发生某种事件(比如鼠标点击,鼠标滑过等)时,毫无疑问子元素和父元素都会接收到该事件,可具体顺序是怎样的呢?冒 ...
- Microsoft Windows Scripting Self-Paced Learning Guide
http://www.mums.ac.ir/shares/hit/eduhit/book/windowsscripting.pdfhttp://support.microsoft.com/kb/926 ...
- JS学习-基础运动
多物体运动 多个物体用同一个函数时,函数里定义的定时器应该要每个物体对应一个定时器名称,不然会导致未完成运动就被关闭了,因为定时器名称一样,而开启定时器前会清除一下. obj.timer 多值同时运动 ...
- 关于github改名问题
不喜欢github显示的目录名字于是百度了下,更改过程,记录下来,方便日后查看! 首页右上角点击出来菜单,找到Settings按钮点击 左侧找到Account账号菜单点击 找到change usern ...
- Scrapy爬虫requests
requests 模块 模块的由来: 浏览器可以浏览网站, 是由于浏览器发送了requests , 各种请求.打开一个网站可能有几十到几百个请求. 从而服务器端会反馈各种因应不同请求生成的数据. 我们 ...
- 扩展运算符&reset运算符
扩展运算符用三个点号表示,功能是把数组或类数组对象展开成一系列用逗号隔开的值 var foo = function(a, b, c) { console.log(a); console.log(b); ...
- Linux基础之-元字符
Bash中的特殊字符,键盘上能敲出来的特殊字符都有其特殊意义,强调一点:元字符是被shell解释的. 1. '',取命令的执行结果 [root@MiWiFi-R3-srv ~]# ls4.txt an ...