spring配置文件标签中resource使用${}占位符加载config.properties配置属性值 灵活加载XML文件

背景:

项目使用mybatis,配置了多数据源1:mysql   2:sqlserver

先部分场景部署只需要一个数据源,导致每次发版本都要手动到.xml文件注释掉一个数据源的配置

现在解决方案:存两份数据库连接配置文件

文件名称存在config.properties文件中:dbXml=app-mybatis

修改主配置文件:<import resource="classpath:${dbXml}.xml"/>

导致报错

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'dbXml' in string value "classpath:${dbXml}.xml"

解决方案:

1.提供实现ApplicationContextInitializer接口的实现类

 

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.support.ResourcePropertySource;

import java.io.IOException;

/**
 * @author     :huchengwei
 * @date       :Created in 2019/10/14 16:45
 * @description:解决Spring默认import动作时在属性文件加载之前。
 * 这样写好处在与你只需修改.properties配置信息便可以动态实现不同引入加载
 * Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'dbXml' in string value "classpath:${dbXml}.xml"
 * @modified By:
 * @version: $
 */
public class CustomerApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        ResourcePropertySource propertySource = null;
        try {
            //dbXml
            propertySource = new ResourcePropertySource("classpath:config.properties");
        } catch (IOException e) {
        }
        String dbXml=(String)propertySource.getProperty("dbXml");
//        propertySource.setProperty();
        applicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
    }

}

2.在web.xml中配置:

<context-param>
  <param-name>contextInitializerClasses</param-name>
  <param-value>com.winning.common.web.context.CustomerApplicationContextInitializer</param-value>
</context-param>

3.在spring的主配置文件中使用

<import resource="classpath:${dbXml}.xml"/>

 

亲测有效

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值