Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 511
Sled Avatar asked Oct 26 '16 17:10

Sled


Video Answer


2 Answers

This should do the trick...

final AnnotationConfigApplicationContext appContext =  new AnnotationConfigApplicationContext();
appContext.getEnvironment().setActiveProfiles( "myProfile" );
appContext.register( com.initech.ReleaserConfig.class );
appContext.refresh();
like image 125
Jamie Bisotti Avatar answered Oct 11 '22 19:10

Jamie Bisotti


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();
like image 31
RajVimalC Avatar answered Oct 11 '22 18:10

RajVimalC