Profile作用
用来解决不同环境下加载不同类、配置的一种方式。例如在项目环境和线上环境数据库配置不同,可用通过Profile机制来激活不同配置。
可以通过配置文件和注解两种方式来使用Profile。
使用Profile
注解方式
主要有以下两个注解:
- @Profile - 标注一个特定环境
- @ActiveProfile - 激活某个环境
public interface DataSource{
String getName();
}
public DevDataSource implements DataSource{
public String getName(){
return "dev-ds";
}
}
public ProductDataSource implements DataSource{
public String getName(){
return "product-ds";
}
}
@Configuration
public class DataSourceConfiguration{
@Bean
@Profile("dev")
public DataSource devDataSource(){
return new DevDataSource();
}
@Bean
@Profile("product")
public DataSource productDataSource(){
return new ProductDataSource();
}
}
激活方式:
JVM参数:-Dspring.profiles.active=dev
标注:@ActiveProfile
配置文件方式
除了默认的 application.properties 文件外,还可以指定application-{profile}.properties的文件
通过JVM参数:-Dspring.profiles.active=dev 来加载相应的配置
网友评论