Spring加载和遍历properties配置文件(绝对路径和类路径)

本文介绍了如何在Spring中通过XML配置加载properties文件,无论是绝对路径还是类路径。在`applicationContext.xml`中进行配置,`mailService.properties`文件内定义属性。`EmailServiceImpl`中实现get和set方法,并在初始化时加载并遍历properties文件的所有键值对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 首先在applicationContext.xml中注入:
<bean name="emailService" class="com.test.mail.service.impl.EmailServiceImpl">
        <property name="emailSendTool" ref="emailSendTool"/>
        <property name="propertiesDefinitionFiles">
            <list>
                <value>${mail.tempate.properties.path:classpath:}tempate.properties</value>
            </list>
        </property>
 </bean>

2.在mailService.properties中定义:
这里可以是用file:后加绝对路径和classpath:加相对类路径的路径两种,xml中定义的默认值是classpath:,即类路径。

mail.tempate.properties.path=file:/opt/administrator/conf/

3.在EmailServiceImpl中加入get和set方法:

import org.springframework.core.io.Resource;

private List<Resource> propertiesDefinitionFiles;

public List<Resource> getPropertiesDefinitionFiles() {
    return propertiesDefinitionFiles;
}

public void setPropertiesDefinitionFiles(List<Resource> propertiesDefinitionFiles) {
    this.propertiesDefinitionFiles = propertiesDefinitionFiles;
}

4.在init中加载并遍历:

private Map<String,String> mailTempateMap = new HashMap();

private String mailContent;

private String mailTempateFile;

public void init() throws IOException {
    for (Resource propertiesDefinitionFile : propertiesDefinitionFiles){
        Properties properties = loadProperties(propertiesDefinitionFile);
        for (Map.Entry<Object,Object> entry : properties.entrySet()){
            mailTempateFile = entry.getValue()+"";
            //load tempate
            mailContent = StringUtils.isBlank(mailTempateFile) ? null : new String(Files.readAllBytes(Paths.get(mailTempateFile)));
            mailTempateMap.put(entry.getKey()+"", mailContent);
        }
    }
}

public static Properties loadProperties(Resource resource) throws IOException {
    Properties properties = new Properties();
    InputStream is = null;
    try {
        is = resource.getInputStream();
        properties.load(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return properties;
}

5.到此为止,就把绝对路径下/类路径下的properties文件加载,并遍历所有的key和value

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值