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

16

简短概述:如何创建基于注解配置类的Spring上下文,同时提供活动配置文件?

我正在尝试使用带有注解指定配置的类来创建Spring上下文。

org.springframework.context.ApplicationContext context = 
    new org.springframework.context.annotation.AnnotationConfigApplicationContext( com.initech.ReleaserConfig.class );

然而,当它启动时会崩溃,因为它找不到必需的bean,但该bean确实存在:尽管仅在特定配置文件"myProfile"

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


PS- 我没有使用Spring Boot,而是使用的是Spring 4.2.4.RELEASE。

2个回答

17

这应该能解决问题...

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

2
@ArtB 在实例化上下文之前,您可以使用 System.setProperty("spring.profiles.active", "myProfile"); - xedo
被接受的答案解决了我的问题,我甚至进行了编辑以包含我所需的缺失细节。 - Sled
或者您可以将Windows系统环境变量设置为SPRING_PROFILES_ACTIVE=myProfile。(如果您通过IDE运行代码,则需要重新启动IDE。) - wonsuc
或者您可以在测试时从IDE的运行配置中添加环境变量SPRING_PROFILES_ACTIVE=myProfile - wonsuc
这最后两条评论描述了设置活动Spring配置文件的非编程方式。这两种方法都是不错的选择;然而,这个问题要求以编程方式完成。 - Jamie Bisotti
显示剩余4条评论

2
如果您想让 classpath:resources/application-${spring.profiles.active}.yml 发挥作用,在刷新之前设置系统属性是可行的方法。
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().getSystemProperties().put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
applicationContext.scan("com.sample");
applicationContext.refresh();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接