背景:
项目使用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"/>
亲测有效