Spring Profiles provide a way to segregate parts of your application configuration.
Any @Component
or @Configuration
can be marked with @Profile
to limit when it is loaded which means that component or configuration will be loaded in the application context only when the active profiles is same as the profile mapped to a component.
To mark a profile active, spring.profiles.active
property must be set in application.properties
or given as an VM argument as -Dspring.profiles.active=dev
While writing Junit, you would want to activate some profile so as to load the required configuration or Component. Same can be achieved by using @ActiveProfile
annotation.
Consider a configuration class which is mapped to profile 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());
}
}
Consider a configuration class which is mapped to profile 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());
}
}
So, if you want to run your junit test cases in dev
profile then you have to use the @ActiveProfile('dev')
annotation. This will load the DataSourceConfig bean defined in dev profile.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ActiveProfiles("dev")
public class Tests{
// Junit Test cases will use the 'dev' profile DataSource Configuration
}
Conclusion
@Profile
is used to map a class to a profile
@ActiveProfile
is used to activate a particular profile(s) during junit test class execution