Spring后端技术Java&Spring基础技术

Spring import配置文件使用占位符

2017-08-24  本文已影响34人  Java技术栈

import使用占位符

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

在配置文件添加配置

db.connection.pool=druid

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

Causedby:java.lang.IllegalArgumentException:Couldnotresolve placeholder'db.connection.pool'invalue"classpath:META-INF/spring/spring-${db.connection.pool}.xml"

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

1、添加AppContextInitializer启动类:

publicclassAppContextInitializer

implementsApplicationContextInitializer{

privateLoggerlogger=Logger.getLogger(AppContextInitializer.class);

@Override

publicvoidinitialize(ConfigurableApplicationContextapplicationContext){

ResourcePropertySourcepropertySource=null;

try{

propertySource=newResourcePropertySource("classpath:config/db-config.properties");

}catch(IOExceptione){

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

}

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

}

}

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

context-param>

contextInitializerClasses

com.example.AppContextInitializer

启动配置文件加载正常。

上一篇 下一篇

猜你喜欢

热点阅读