ConfigurableApplicationContext ctx =
new AnnotationConfigApplicationContext("com.manuel.jordan.config");
ctx.getEnvironment().setActiveProfiles("jdbc", "mysql");
...
Here you have to watch out! Your active profiles are jdbc
and mysql
as expected. But NO beans were created based on those profiles!
In the second approach with System.setProperty("spring.profiles.active", "jdbc, mysql");
(before creating the ApplicationContext
) beans will be created based on those profiles!
Demo
@Configuration
public class MyConfiguration {
@Bean(name = "jdbc")
@Profile("jdbc")
public MyProfileClass jdbc(){
return new MyProfileClass("jdbc");
}
@Bean(name = "mysql")
@Profile("mysql")
public MyProfileClass mysql(){
return new MyProfileClass("mysql");
}
@Bean(name = "notJdbc")
@Profile("!jdbc")
public MyProfileClass notJdbc(){
return new MyProfileClass("not jdbc");
}
@Bean(name = "notMysql")
@Profile("!mysql")
public MyProfileClass notMysql(){
return new MyProfileClass("not mysql");
}
}
public class MyProfileClass {
private final String name;
public MyProfileClass(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class DemoApplication {
public static void main(String[] args) {
// System.setProperty("spring.profiles.active", "jdbc,mysql");
ConfigurableApplicationContext ctx =
new AnnotationConfigApplicationContext("com.manuel.jordan.config");
ctx.getEnvironment().setActiveProfiles("jdbc", "mysql"); // to late beans based on profile already created
System.out.println(Arrays.asList(ctx.getEnvironment().getActiveProfiles()));
for (String beanName:ctx.getBeanDefinitionNames()) {
System.out.println(ctx.getBean(beanName));
}
}
}
There are more options to activate different profiles: Baeldung :: Spring Profiles
UPDATE
When you want to set the active profiles programmatically use, you need to refresh the context.
like:
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("jdbc", "mysql");
ctx.scan("com.manuel.jordan.config");
ctx.refresh();