工具從古至今都是為了方便人們生活和工作的利器,在程序語言中也不例外翰守,Spring具有很多工具類鞭达,有的是專屬框架工具類,而有的是開放給開發(fā)者使用的工具類槐臀,那么我們今天要講的呢就是Spring中的utils锄蹂,一起來看看吧!
前言
Spring的工具類都是以Utils結(jié)尾水慨,所以要查看這些工具類得糜,只需要在API文檔中查詢所有*Utils即可敬扛,可以看到有多達(dá)幾十個。其中有我們非常熟悉的org.springframework.util.StringUtils掀亩,有用到過的org.springframework.aop.support.AopUtils舔哪,還有可能沒有聽過的org.springframework.core.annotation.AnnotatedElementUtils等等。后面我們會選擇十來個有用的Utils槽棍,給大家展示一下Spring中的工具類的有用和常用方法捉蚤。
org.springframework.core.io.support.PropertiesLoaderUtils
我們今天第一個介紹的是PropertiesLoaderUtils,這個工具類主要是針對Properties文件的加載操作炼七,在Spring對.properties文件和.factories文件的操作都有使用到缆巧。
先來簡單看看這個類提供的有用方法:
- Properties loadProperties(Resource resource) throws IOException:從一個資源文件加載Properties;
- Properties loadProperties(EncodedResource resource) throws IOException:加載資源文件豌拙,傳入的是提供了編碼的資源類(EncodedResource)陕悬;和上面方法基本一致;
- void fillProperties(Properties props, Resource resource) throws IOException:從一個資源類中加載資源按傅,并填充到指定的Properties對象中捉超;
- void fillProperties(Properties props, EncodedResource resource)
throws IOException:從一個編碼資源類中加載資源,并填充到指定的Properties對象中唯绍;和上面方法基本一致拼岳; - Properties loadAllProperties(String resourceName) throws IOException:根據(jù)資源文件名稱,加載并合并classpath中的所有資源文件况芒;
- Properties loadAllProperties(String resourceName, ClassLoader classLoader) throws IOException:從指定的ClassLoader中惜纸,根據(jù)資源文件名稱,加載并合并classpath中的所有資源文件绝骚;
方法不是很多耐版,而且共性較大,我們就從最簡單的Properties loadProperties(Resource resource)開始压汪。
loadProperties
測試方法很簡單粪牲,我們首先準(zhǔn)備一個test.properties文件,放到resources下面:
key=value
key2=\u4E2D\u6587
完成代碼:
@Test
public void testLoadPropertiesResource() throws Exception {
Properties ret = PropertiesLoaderUtils
.loadProperties(new ClassPathResource("test.properties"));
assertEquals("value", ret.getProperty("key"));
assertEquals("中文", ret.getProperty("key2"));
}
測試完成止剖。沒有太大難度虑瀑; 但是,其實(shí)Properties對象不僅僅支持.properties文件滴须,還支持XML格式的資源配置文件舌狗。先來看看Properties對象對XML類型資源文件的DTD定義(http://java.sun.com/dtd/properties.dtd):
<!ELEMENT properties ( comment?, entry* ) >
<!ATTLIST properties version CDATA #FIXED "1.0">
<!ELEMENT comment (#PCDATA) >
<!ELEMENT entry (#PCDATA) >
<!ATTLIST entry key CDATA #REQUIRED>
那么我們就可以有以下測試。創(chuàng)建一個text.xml文件在classpath下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>一些自定義說明</comment>
<entry key="key">value</entry>
<entry key="key2">中文</entry>
</properties>
完成測試代碼:
@Test
public void testLoadPropertiesResourceXml() throws Exception {
Properties ret = PropertiesLoaderUtils
.loadProperties(new ClassPathResource("test.xml"));
assertEquals("value", ret.getProperty("key"));
assertEquals("中文", ret.getProperty("key2"));
}
測試通過扔水。當(dāng)然痛侍,我們是非常不建議使用XML的方式來做配置的。
接下來使用EncodeResource來測試,EncodeResource在Resource上增加了字符編碼設(shè)置主届。同樣使用之前的test.properties:
@Test
public void testLoadPropertiesEncodedResource() throws Exception {
Properties ret = PropertiesLoaderUtils.loadProperties(
new EncodedResource(new ClassPathResource("test.properties"),
"UTF-8"));
assertEquals("value", ret.getProperty("key"));
assertEquals("中文", ret.getProperty("key2"));
}
可以看到赵哲,只是在之前的ClassPathResource基礎(chǔ)之上包裝了UTF-8字符編碼的EncodeResource;
loadAllProperties
loadProperties方法君丁,從當(dāng)前classpath下加載properties文件枫夺,如果使用loadAllProperties,可以從當(dāng)前classpath下加載所有的相同名稱的properties文件绘闷,并執(zhí)行合并橡庞。
來完成一個測試。把上一個例子中的test.properties文件保留印蔗,放到src/main/resources中扒最;然后在src/test/resources目錄下再創(chuàng)建一個test.properties文件,內(nèi)容為:
key3=value
測試代碼:
@Test
public void testLoadAllPropertiesString() throws Exception {
Properties ret = PropertiesLoaderUtils
.loadAllProperties("test.properties");
assertEquals("value", ret.getProperty("key"));
assertEquals("value", ret.getProperty("key3"));
}
執(zhí)行測試通過华嘹;可以看到吧趣,main下的test.properties和test下的test.properties都被識別并執(zhí)行了合并;那如果在test/resources中的test.properties中增加
key=update
再次執(zhí)行測試耙厚,仍然通過强挫,說明在多個配置文件中如果有重復(fù)key,最近的classpath為準(zhǔn)(比如當(dāng)前應(yīng)用的properties內(nèi)容會優(yōu)先于jar包中的properties)
但是薛躬,如果這種情況下纠拔,使用loadProperties方法,那么只會加載到test/resources中的test.properties泛豪;這個結(jié)果可以對loadAllProperties有更深刻理解。
fillProperties
fillProperties方法其實(shí)是loadProperties方法的真正調(diào)用方法侦鹏。先來看看測試代碼:
@Test
public void testFillPropertiesPropertiesResource() throws Exception {
Resource res = new ClassPathResource("test.properties");
Properties ret = new Properties();
PropertiesLoaderUtils.fillProperties(ret, res);
assertEquals("value", ret.getProperty("key"));
}
使用非常簡單诡曙。
我們來看一下loadProperties方法的源代碼:
/**
Load properties from the given EncodedResource,
potentially defining a specific encoding for the properties file.
@see #fillProperties(java.util.Properties, EncodedResource)
*/
public static Properties loadProperties(EncodedResource resource) throws IOException {
Properties props = new Properties();
fillProperties(props, resource);
return props;
}
可以看到,其實(shí)調(diào)用的就是fileProperties方法略水,而這個方法的實(shí)現(xiàn)其實(shí)也很簡單:
public static void fillProperties(Properties props, EncodedResource resource)
throws IOException {
fillProperties(props, resource, new DefaultPropertiesPersister());
}
代理給了fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister)方法价卤;只是最后一個參數(shù)是一個PropertiesPersister,抽取了一個統(tǒng)一的從XML或者properties資源加載和裝載接口渊涝;來看看具體實(shí)現(xiàn)(我只保留了最基本的關(guān)鍵代碼):
static void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister)
throws IOException {
InputStream stream = null;
Reader reader = null;
try {
String filename = resource.getResource().getFilename();
//如果是XML文件慎璧,
if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
stream = resource.getInputStream();
persister.loadFromXml(props, stream);
}else {
stream = resource.getInputStream();
persister.load(props, stream);
}
}finally {
//close方法
}
}
可以看到,其實(shí)就是調(diào)用了PropertiesPersister的loadFromXml和load方法來分別加載XML或properties跨释;
如果再往下看胸私,有興趣的童鞋可以看看DefaultPropertiesPersister的相關(guān)的這兩個方法,其實(shí)核心還是使用Properties對象的load和loadFromXML方法完成的鳖谈。
小結(jié)
本節(jié)中岁疼,簡單介紹了Spring的第一個Utils:PropertiesLoaderUtils,后面持續(xù)送上更多工具類的介紹缆娃。