Spring 获取propertise文件中的值

时间:2023-03-09 09:25:17
Spring 获取propertise文件中的值

Spring 获取propertise文件中的值

  Spring 获取propertise的方式,除了之前的博文提到的使用@value的注解注入之外,还可以通过编码的方式获取,这里主要说的是要使用EmbeddedValueResolverAware接口的使用。

一、准备propertise文件

Spring 获取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,通过工具类,传入需要获取的参数名,获取对应的参数值。