首页 > 解决方案 > SpringBoot 并使用/加载动态的“applicationContext.xml”而不是硬编码的

问题描述

我见过一百个这样的例子:

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:applicationContext.xml")
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

我已经在兔子小道上走了好几个小时了。

我正在构建一个框架......并且我需要从 xml 依赖注入文件(又名“bean”)中加载(少数依赖项,而不是全部......):

应用程序上下文.xml

我需要命名为动态的,而不是硬编码的。

String myValue = "DefaultEnvVarValue";
String envValue = System.getenv("MYENVVARIABLENAME");
if (null != envValue )
{
     myValue=envValue;
}
String topLevelAppContextFileName = "applicationContext." + myValue + ".xml";

没有springboot,我会这样做:

 ApplicationContext context = new ClassPathXmlApplicationContext(topLevelAppContextFileName);

有没有办法用 SpringBoot 解决这个问题?

我为属性文件找到了 PropertySourcesPlaceholderConfigurer,但找不到任何依赖注入的东西。

边注:

在我收到“xml bad”评论之前,我的大部分依赖项都是基于注释的。但是我正在制作一个供其他人使用的框架,因此我需要其中的一些是 xml 驱动的.....aka,我有正当理由让一些 DI 是 xml 驱动的。

标签: spring-bootspring-bean

解决方案


这可以工作 -

配置

public class DemoApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

     @Override
     public void initialize(ConfigurableApplicationContext ac) {
      ac = new ClassPathXmlApplicationContext(topLevelAppContextFileName);
     }
}

主要的

    public static void main(String args[]) {
         new SpringApplicationBuilder(Application.class)
            .initializers(new DemoApplicationContextInitializer())
            .run(
    }

推荐阅读