Spring Profiles 提供了一种分离应用程序配置部分的方法。
任何@Component 或@Configuration 都可以用@Profile 标记以限制加载时间,这意味着只有当活动配置文件与映射到的配置文件相同时,组件或配置才会在应用程序上下文中加载组件。
要将配置文件标记为活动,必须在application.properties 中设置spring.profiles.active 属性或作为-Dspring.profiles.active=dev 的VM 参数给出
在编写 Junit 时,您可能希望激活一些配置文件以加载所需的配置或组件。使用@ActiveProfile注解也可以达到同样的效果。
考虑一个映射到配置文件dev的配置类
@Configuration
@Profile("dev")
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost/test");
ds.setUsername("root");
ds.setPassword("mnrpass");
return ds;
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
}
考虑一个映射到配置文件prod的配置类
@Configuration
@Profile("prod")
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:oracle://xxx.xxx.xx.xxx/prod");
ds.setUsername("dbuser");
ds.setPassword("prodPass123");
return ds;
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
}
因此,如果您想在 dev 配置文件中运行您的 junit 测试用例,那么您必须使用 @ActiveProfile('dev') 注释。这将加载在 dev 配置文件中定义的 DataSourceConfig bean。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ActiveProfiles("dev")
public class Tests{
// Junit Test cases will use the 'dev' profile DataSource Configuration
}
结论
@Profile 用于将类映射到配置文件
@ActiveProfile 用于在 junit 测试类执行期间激活特定配置文件