For Spring Framework
6 having some @Configuration
classes with the @Profile("default")
and @Profile("prod")
respectively. Exists the following scenarios:
Scenario I
ctx = new AnnotationConfigApplicationContext("com.manuel.jordan.config");
When is executed the Main
class with the -Dspring.profiles.default=default,prod
property, through:
System.out.println("Default Profiles");
for(String defaultProfile : ctx.getEnvironment().getDefaultProfiles()) {
System.out.println(" " + defaultProfile);
}
I can see both profiles being listed and is possible retrieve the @Bean
from these @Configuration
classes based with the @Profile("default")
and @Profile("prod")
profiles. Until here all work as expected. Therefore is confirmed that these two default profiles were applied to the Spring Application Context for the beans creation process.
Scenario II
With
ctx = new AnnotationConfigApplicationContext("com.manuel.jordan.config");
ctx.getEnvironment().setDefaultProfiles("default", "prod");
or even with
ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setDefaultProfiles("default", "prod");
ctx.scan("com.manuel.jordan.config");
ctx.refresh();
When is executed the Main
class without the -Dspring.profiles.default=default,prod
property, because now is used .setDefaultProfiles("default", "prod")
instead, through:
System.out.println("Default Profiles");
for(String defaultProfile : ctx.getEnvironment().getDefaultProfiles()) {
System.out.println(" " + defaultProfile);
}
I can see both profiles being listed but is not possible retrieve the @Bean
from these @Configuration
classes, again, based with the @Profile("default")
and @Profile("prod")
profiles - both profiles were ignored because each one throws the NoSuchBeanDefinitionException
type. Why here is failing?
Questions
- Why did
-Dspring.profiles.default=default,prod
work and.setDefaultProfiles("default", "prod")
did not work? - Is it a bug?
This situation was shared on SO at:
Comment From: snicoll
You already asked that before, see https://github.com/spring-projects/spring-framework/issues/30385#issuecomment-1524817262. Setting the profile when the context has refreshed isn't going to help. Can't you see in the first example that you're setting the profiles and then nothing else happens and your context has been refreshed? That's because it all happens in the previous line.
As for the second example, I can't reproduce. If you can, then please share a small app created from start.spring.io that reproduces the problem and we can reconsider.