spring:PropertyPlaceholderConfigurer用法-获取properties属性

PropertyPlaceholderConfigurer用于读取*.properties属性文件。

用法一:自动注入配置属性

在spring容器启动前,必须配置扫描用到的properties文件


接下来,创建一个spring  @Configuration

@Configuration
class MyConfig {
    @Value("${data}")
    private String data;
    public String getData() {
        return data;
    }
}

用法二:重写PropertyPlaceholderConfigurer,动态解析属性(适用于配置项不固定的场景)

组件配置:


   
       classpath:channel.properties
   

show code:这个动态获取多个channel的配置

@Component
public class ChannelConfig extends PropertyPlaceholderConfigurer {
	private static Map mapList = new HashMap();

    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")
            ));
        }
    }
}

参考文章:

https://www.cnblogs.com/Gyoung/p/5507063.html

你可能感兴趣的:(Java)