PropertyPlaceholderConfigurer用于读取*.properties属性文件。
用法一:自动注入配置属性
在spring容器启动前,必须配置扫描用到的properties文件
<!-- 自动读取配置文件 -->
<context:property-placeholder location="classpath:*.properties"/>
接下来,创建一个spring @Configuration
@Configuration
class MyConfig {
@Value("${data}")
private String data;
public String getData() {
return data;
}
}
用法二:重写PropertyPlaceholderConfigurer,动态解析属性(适用于配置项不固定的场景)
组件配置:
<bean class="">
<property name="location">
<value>classpath:</value>
</property>
</bean>
show code:这个动态获取多个channel的配置
@Component
public class ChannelConfig extends PropertyPlaceholderConfigurer {
private static Map<String, Channel> mapList = new HashMap<String, Channel>();
public ChannelConfig() {
}
public Channel getChannel(String channelName) {
return (channelName) ? (channelName) : null;
}
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
(beanFactoryToProcess, props);
for (Object keySet : ()) {
String key = ();
String[] keyPartArr = ("\\.");
if ( != 3) {
continue;
}
String channelName = keyPartArr[1];
if ((channelName)) {
continue;
}
(channelName, new Channel(
("mail." + channelName + ".host"),
("mail." + channelName + ".port"),
("mail." + channelName + ".username"),
("mail." + channelName + ".password"),
("mail." + channelName + ".sendFrom")
));
}
}
}
参考文章:
/Gyoung/p/