tl;博士:如何在提供事件配置文件的同时基于基于注释的配置类创建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上。

最佳答案

这应该可以解决问题...

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

09-10 07:20
查看更多