Spring 獲取propertise的方式,除了之前的博文提到的使用@value的註解注入之外,還可以通過編碼的方式獲取,這裏主要說的是要使用EmbeddedValueResolverAware接口的使用。
一、準備propertise文件
在資源文件夾下面建立好要測試需要的app.propertise文件,裏面寫幾條測試數據,本文主要如圖數據。
二、準備配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.lilin"></context:component-scan> <!-- spring的屬性加載器,加載properties文件中的屬性 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>classpath:app.properties</value> </property> <property name="fileEncoding" value="utf-8" /> </bean> </beans>
配置文件中主要包含了兩部分,都是用於測試的,一個是註解掃描的路徑定義,讓後面的測試類,在當前的掃描路徑下,可以讓spring管理be;一個是propertise文件的加載配置PropertyPlaceholderConfigurer,配置文件的讀取路徑和編碼方式。
三、準備工具類
package com.lilin.maven.service.dynamicBean; import org.springframework.context.EmbeddedValueResolverAware; import org.springframework.stereotype.Service; import org.springframework.util.StringValueResolver; @Service public class PropertiesUtils implements EmbeddedValueResolverAware { private StringValueResolver stringValueResolver; @Override public void setEmbeddedValueResolver(StringValueResolver resolver) { stringValueResolver = resolver; } public String getPropertiesValue(String name) { name = "${" + name + "}"; return stringValueResolver.resolveStringValue(name); } }
工具類實現EmbeddedValueResolverAware接口,實現必須的setEmbeddedValueResolver方法,把方法的resolver參數,賦值給當前工具類的私有屬性,同時暴露出對外的提取函數getPropertiesValue,通過名稱獲取當前的對應的值。特別注意的是,resolveStringValue函數接受的name參數,一定是轉換成“${name}”的方式才行,否則是取不到值的。
四、準備測試類
/** * */ package com.lilin.maven.service.dynamicBean; import javax.annotation.Resource; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; import com.lilin.maven.service.BaseTest; /** * @author lilin * */ @ContextConfiguration(locations = { "classpath:/config/spring/spring-test.xml" }) public class DynamicBeanTest extends BaseTest { @Resource private PropertiesUtils propertiesUtils; @Test public void test() { String beanName = propertiesUtils.getPropertiesValue("a"); System.out.println(beanName); String beanName1 = propertiesUtils.getPropertiesValue("b"); System.out.println(beanName1); } }
測試類,主要使用testNG的測試方式,testNG的使用在前面的博文中已經有所介紹,請自行參閱。測試類中,把工具類注入PropertiesUtils,通過工具類,傳入需要獲取的參數名,獲取對應的參數值。