Spring import配置文件使用占位符

来源:互联网 发布:通达信软件编程 编辑:程序博客网 时间:2024/05/21 22:17


import使用占位符

连接池切换导入配置的代码:

  1. <import resource="classpath:META-INF/spring/spring-${db.connection.pool}.xml" />

在配置文件添加配置

  1. db.connection.pool=druid

启动直接报错,读取不到配置,因为属性文件的加载在import配置文件之后。

  1. Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'db.connection.pool' in value "classpath:META-INF/spring/spring-${db.connection.pool}.xml"

所以,要在应用启动的时候添加属性

1、添加AppContextInitializer启动类:

  1. public class AppContextInitializer

  2.        implements ApplicationContextInitializer<ConfigurableApplicationContext> {

  3.    private Logger logger = Logger.getLogger(AppContextInitializer.class);

  4.    @Override

  5.    public void initialize(ConfigurableApplicationContext applicationContext) {

  6.        ResourcePropertySource propertySource = null;

  7.        try {

  8.            propertySource = new ResourcePropertySource("classpath:config/db-config.properties");

  9.        } catch (IOException e) {

  10.            logger.error("加载配置文件[config/db-config.properties]失败");

  11.        }

  12.        applicationContext.getEnvironment().getPropertySources().addFirst(propertySource);

  13.    }

  14. }

2、在web.xml中添加配置:

  1. context-param>  

  2.    <param-name>contextInitializerClasses</param-name>  

  3.    <param-value>com.example.AppContextInitializer</param-value>  

  4. </context-param>

启动配置文件加载正常。


阅读全文
0 0