PropertyPlaceholderConfigurer實現配置文件讀取
PropertyPlaceholderConfigurer類的主要的用法是將BeanFactory里定義的內容放在一個.properties的文件中. PropertyPlaceholderConfigurer是個bean工廠后置處理器的實現,也就是BeanFactoryPostProcessor接口的一個實現. PropertyPlaceholderConfigurer可以將上下文(配置文件)中的屬性值放在另一個單獨的標準java Properties文件中去. 這樣的話,我只需要對properties文件進行修改,而不用對xml配置文件進行修改.
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;/*** 配置讀取工具* Created by zhengzhihust on 15/9/23.*/
public class ExampleConfigure extends PropertyPlaceholderConfigurer {@Overrideprotected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {super.processProperties(beanFactory, props);List<String> topics = new ArrayList<>();for (Map.Entry<Object, Object> entry : props.entrySet()) {//讀取配置文件中的信息}}
}
當然,spring.xml配置文件還需要引用一下資源文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.mogujie.com/schema/tesla http://www.mogujie.com/schema/tesla/tesla.xsd"><bean id="id" class="全限定類名"><property name="locations"><list><value>classpath:conf/example.properties</value></list></property></bean></beans>
原文參考:http://zhengzhihust.github.io/jekyll/update/2016/03/27/java-place-holder