如何以编程方式创建Spring上下文时设置活动配置文件?

Sle*_*led 8 spring programmatically

tl; dr:如何在提供活动配置文件的同时基于基于注释的配置类创建Spring上下文?

我正在尝试使用具有使用注释指定的配置的类来创建Spring上下文.

org.springframework.context.ApplicationContext context = 
    new org.springframework.context.annotation.AnnotationConfigApplicationContext( com.initech.ReleaserConfig.class );
Run Code Online (Sandbox Code Playgroud)

但是当它启动时崩溃,因为它无法找到所需的bean,但该bean确实存在:尽管只在某个配置文件下"myProfile".

如何指定活动配置文件?我有一种感觉,我需要使用一个org.springframework.context.annotation.AnnotationConfigApplicationContext(org.springframework.beans.factory.support.DefaultListableBeanFactory)构造函数,但我不确定哪些是合适的.


PS-我没有使用Spring Boot,但是在Spring 4.2.4.RELEASE上.

Jam*_*tti 9

这应该是诀窍......

final AnnotationConfigApplicationContext appContext =  new AnnotationConfigApplicationContext();
appContext.getEnvironment().setActiveProfiles( "myProfile" );
appContext.register( com.initech.ReleaserConfig.class );
appContext.refresh();
Run Code Online (Sandbox Code Playgroud)

  • @ArtB,您可以在实例化上下文之前使用`System.setProperty(“ spring.profiles.active”,“ myProfile”);` (2认同)