spring-boot - 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 驱动的。
解决方案
这可以工作 -
配置
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(
}
推荐阅读
- amazon-web-services - 使用 Get Request 在 ElasticSearch 中搜索
- ruby - 尝试安装 ruby gem gosu 时出错
- javascript - 如何旋转形状?
- sql - 动态 XML 到 SQL - SQL Server
- wordpress - 自定义 Woocommerce 存档页面 URL ('/page/')
- netlogo - 海龟在特定的补丁颜色上改变颜色
- scala - Scala实现内联特征方法
- mysql - mysql的MS访问错误
- python - 有效地将元组列表转换为具有相应总和的集合
- powershell - 执行 Invoke-expression 时,Powershell 脚本在运行时退出