我们实际开发中往往有多个环境,比如测试环境、开发环境、生产环境等;不同的环境往往配置也有区别,一直切换环境的配置很麻烦,Spring 为我们提供了一个注解,可以快速切换环境配置。
我们新建一个配置,作用是注册三个数据源,因为不同的环境使用的数据库一般不一样:
@Configuration
@PropertySource("classpath:/person.properties")
public class MainConfigOfProfile implements EmbeddedValueResolverAware {
@Value("${db.user}")
private String user;
@Value("${db.url}")
private String url;
private String driver;
// 指定组件在那个环境下才能注册到组件中: 不指定则都能注册
@Profile("test")
@Bean("testDataSource")
public DataSource dataSourceTest(@Value("${db.password}") String pwd) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(pwd);
dataSource.setJdbcUrl(url);
dataSource.setDriverClass(driver);
return dataSource;
}
@Profile("dev")
@Bean("devDataSource")
public DataSource dataSourceDev(@Value("${db.password}") String pwd) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(pwd);
dataSource.setJdbcUrl(url);
dataSource.setDriverClass(driver);
return dataSource;
}
@Profile("prod")
@Bean("prodDataSource")
public DataSource dataSourceProd(@Value("${db.password}") String pwd) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(user);
dataSource.setPassword(pwd);
dataSource.setJdbcUrl(url);
dataSource.setDriverClass(driver);
return dataSource;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.driver = resolver.resolveStringValue("${db.driver}");
}
}
这里在方法上使用了 @Profile
注解来表示对应的环境,也就是说当指定环境之后,只有标注对应环境名的 Bean 才能被注册到容器中去,没有标注任何 @Profile
的方法默认直接注册进去。
环境区分好了如何启动对应的环境?
有两种方式:
在 IDEA 中可以设置启动参数,加上如下参数:
-Dspring.profiles.active=test
其中 test
可以换成在 @Profile
中配置的名称。
这样就能指定环境启动了,还可以使用无参构造创建容器。
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("prod", "dev");
context.register(MainConfigOfProfile.class);
context.refresh();
都是可以的,这里同时指定了两个环境:prod
和 dev
。
@Profile
也可以放在类上,这样整个类就对应指定的环境名。
在 IDEA 中,还可以使用图形化界面快速切换所在的环境。