【问题标题】:Conditionally load application context有条件地加载应用程序上下文
【发布时间】:2015-04-28 19:12:53
【问题描述】:

如何从两个位置之一加载spring-beans xml 文件?

  • System.getProperty("conf.dir") + "/context.xml" 如果存在,则回退到
  • classpath:/context.xml

这是我开始的,但我想加载第一个找到的上下文

@Configuration
@ImportResource({"${conf.dir}/context.xml", "classpath:/context.xml"})
public class AppConfig {
     @Autowire somethingFromAboveXmlContext;
}

我研究了@Conditional,但解决方案变得有点不直观。

@Configuration
@Conditional(AppContextCondition.class)
@ImportResource("${conf.dir}/context.xml")
@ImportResource("classpath:/context.xml")
public class AppConfig {
     @Autowire somethingFromAboveXmlContext;
}

是否有手动方法来执行 ImportResource 所做的事情?

【问题讨论】:

  • 也可以使用@profile 注解来完成。链接:gordondickens.com/wordpress/2012/06/12/…
  • @anuraggupta 可以吗?这不是一个配置文件类型的设置,而是一个如果存在的话就接受这个类型的场景

标签: java spring conditional applicationcontext


【解决方案1】:

你可以试试这个:

@Configuration
@ImportResource({"${conf.dir}/context.xml"})
public class AppConfig {
 static {
    if(!System.getProperties().contains("conf.dir")) {
        System.setProperty("conf.dir", "classpath:");
    }
 }
 @Autowire somethingFromAboveXmlContext;
}

我同意这可能不是一个完美的解决方案,但它可以工作!

【讨论】:

    猜你喜欢
    • 2016-07-06
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2011-05-13
    • 2012-10-04
    • 1970-01-01
    • 2021-07-27
    • 2018-12-25
    相关资源
    最近更新 更多