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 id="mailChannelConfig" class="com.bytrees.mail.ChannelConfig">
<property name="location">
<value>classpath:channel.properties</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 mapList.containsKey(channelName) ? mapList.get(channelName) : null;
}
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
for (Object keySet : props.keySet()) {
String key = keySet.toString();
String[] keyPartArr = key.split("\\.");
if (keyPartArr.length != 3) {
continue;
}
String channelName = keyPartArr[1];
if (mapList.containsKey(channelName)) {
continue;
}
mapList.put(channelName, new Channel(
props.getProperty("mail." + channelName + ".host"),
props.getProperty("mail." + channelName + ".port"),
props.getProperty("mail." + channelName + ".username"),
props.getProperty("mail." + channelName + ".password"),
props.getProperty("mail." + channelName + ".sendFrom")
));
}
}
}
参考文章:
版权声明:本文为loophome原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。