- 首先在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