tl;dr: how to create a Spring context based on an annotation-based configuration class, while supplying active profiles?
I am trying to create a Spring context using a class with the configuration specified using annotations.
org.springframework.context.ApplicationContext context =
new org.springframework.context.annotation.AnnotationConfigApplicationContext( com.initech.ReleaserConfig.class );
However when it starts up it crashes because it cannot find a required bean, but that bean does exist : albeit only under a certain profile "myProfile"
.
How do I specify the active profile? I have a feeling I need to use one the org.springframework.context.annotation.AnnotationConfigApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory)
constructor but I'm not sure which ones is appropriate.
PS- I am not using Spring Boot, but am on Spring 4.2.4.RELEASE.
This should do the trick...
final AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.getEnvironment().setActiveProfiles( "myProfile" );
appContext.register( com.initech.ReleaserConfig.class );
appContext.refresh();
If you want classpath:resources/application-${spring.profiles.active}.yml to be working, setting system properties before refreshing is the way to go.
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().getSystemProperties().put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
applicationContext.scan("com.sample");
applicationContext.refresh();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With