背景:
項目使用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"/>
親測有效