How to set the active profile when creating Spring context programmatically?

Sled picture Sled · Oct 26, 2016 · Viewed 8.3k times · Source

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.

Answer

Jamie Bisotti picture Jamie Bisotti · Oct 26, 2016

This should do the trick...

final AnnotationConfigApplicationContext appContext =  new AnnotationConfigApplicationContext();
appContext.getEnvironment().setActiveProfiles( "myProfile" );
appContext.register( com.initech.ReleaserConfig.class );
appContext.refresh();