【问题标题】:How to set the active profile when creating Spring context programmatically?以编程方式创建 Spring 上下文时如何设置活动配置文件?
【发布时间】:2017-03-09 04:35:35
【问题描述】:

tl;dr:如何基于基于注解的配置类创建 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。

【问题讨论】:

    标签: spring programmatically


    【解决方案1】:

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

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

    【讨论】:

    • 这不起作用,因为实例化应用程序上下文会导致异常,所以我永远无法调用.getEnvironment()
    • 你的回答导致了解决方案,所以我完成了它以便它工作
    • @ArtB 你可以在实例化上下文之前使用System.setProperty("spring.profiles.active", "myProfile");
    • 嗨@ArtB 你是怎么解决这个问题的?你能分享更多信息吗?我也遇到了同样的问题在这里找到我的问题stackoverflow.com/questions/46422271/…
    • 接受的答案解决了我的问题,我什至编辑了我需要的缺失细节。
    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2017-09-05
      • 2015-09-24
      • 2017-07-27
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多