在Spring Test配置上使用@Profile和@ActiveProfiles有什么区别
@Configuration
@EnableRetry
@ActiveProfiles("unittest")
static class ContextConfiguration {
Run Code Online (Sandbox Code Playgroud)
和
@Configuration
@EnableRetry
@Profile("unittest")
static class ContextConfiguration {
Run Code Online (Sandbox Code Playgroud)
cse*_*cse 10
简而言之,@Profile定义一个类似调试配置文件和生产配置文件等的配置文件...但是@ActiveProfiles在a的情况下进入图片ApplicationContext并定义ApplicationContext在使用相应的配置文件时应该激活哪些配置文件.
如Spring官方网站JavaDoc中所述:
概要文件是一个命名的逻辑分组,可以通过ConfigurableEnvironment.setActiveProfiles(java.lang.String ...)以编程方式激活,也可以通过将spring.profiles.active属性设置为JVM系统属性,环境变量或者声明为Web应用程序的web.xml中的Servlet上下文参数.也可以通过@ActiveProfiles注释在集成测试中以声明方式激活配置文件.
ActiveProfiles是一个类级别注释,用于声明在为测试类加载ApplicationContext时应使用哪些活动Bean定义概要文件.
此外,您可以在此处查看有关@Profile的更多信息
小智 7
Spring Profiles提供了一种隔离应用程序配置各部分的方法。
任何@Component或@Configuration可以用标记@Profile以限制其加载时间,这意味着仅当活动配置文件与映射到组件的配置文件相同时,组件或配置才会在应用程序上下文中加载。
要将配置文件标记为活动,spring.profiles.active必须在application.propertiesVM参数中设置属性或将属性设置为-Dspring.profiles.active=dev
在编写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());
}
}
Run Code Online (Sandbox Code Playgroud)
考虑一个映射到配置文件的配置类 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());
}
}
Run Code Online (Sandbox Code Playgroud)
因此,如果要在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
}
Run Code Online (Sandbox Code Playgroud)
结论
@Profile 用于将类映射到配置文件
@ActiveProfile 用于在junit测试类执行期间激活特定配置文件
任何@Component 或@Configuration 都可以用@Profile标记以限制加载时间。
您@Profile为您定义:
@Component,包括@Configuration类@Bean然后在测试时,您可以通过在@ActiveProfiles.
ActiveProfiles是一个类级别的注释,用于声明在为测试类加载 ApplicationContext 时应使用哪些活动 bean 定义配置文件。
如果在测试上下文之外使用它没有任何效果。
您将配置文件分配给您的组件@Profile;测试时用 选择它们@ActiveProfiles,开发时用spring.profiles.active属性选择它们。
| 归档时间: |
|
| 查看次数: |
7013 次 |
| 最近记录: |