获取properties属性文件里的信息:俩种方式
首先需要将属性文件交给spring容器!如下:
<!-- 使用注解注入properties中的值 (将属性文件里的信息交给spring来管理) -->
<bean id="projectInfo" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
<!-- 设置编码格式 -->
<property name="fileEncoding" value="UTF-8"></property>
</bean>
方法一:需要写属性文件的对应的实体类!再在实体类的属性上用@value(“#{beanId[key]}”)标签,将属性文件里的值注入到对象属性里!如下:
package com.property;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("configProperty")
public class ConfigProperty {
@Value("#{projectInfo[author_name]}")
private String author_name;
@Value("#{projectInfo[project_info]}")
private String project_info;
public String getAuthor_name() {
return author_name;
}
public void setAuthor_name(String author_name) {
this.author_name = author_name;
}
public String getProject_info() {
return project_info;
}
public void setProject_info(String project_info) {
this.project_info = project_info;
}
}
单元测试:
/**
* 测试 Spring注解方式注入properties文件内容
* @author yuanjz
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:WebRoot/WEB-INF/test-servlet.xml"})
public class PropertiesFactoryTest {
@Resource(name="configProperty")
private ConfigProperty configProperty;
/**
* 该方式需要写配置文件(config.properties)对应的实体类 并且使用@value注解给实体类属性注入值,比较麻烦!
*/
@Test
public void test(){
System.out.println("方式一:"+configProperty.getAuthor_name());
System.out.println("方式一:"+configProperty.getProject_info());
}
}
方法二:使用java.util.properties类 与spring结合的方式,来获取配置文件(config.properties)里的属性值!
说白了就是:属性文件注册到spring容器中,成为一个bean!再在代码中将该bean注入到properties对象中!
不需要实体类,直接可以单元测试!如下:
/**
* 测试 Spring注解方式注入properties文件内容
* @author yuanjz
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:WebRoot/WEB-INF/test-servlet.xml"})
public class PropertiesFactoryTest {
/*将spring容器里的属性文件信息注入到Properties对象里!*/
@Resource(name="projectInfo")
private Properties projectInfo;
/**
* 使用java.util.properties类 与spring结合的方式,来获取配置文件(config.properties)里的属性值!
说白了就是:属性文件注册到spring容器中,成为一个bean!再在代码中将该bean注入到properties对象中!
*/
@Test
public void test2(){
projectInfo.getProperty("author_name");
projectInfo.getProperty("project_info");
System.out.println("方式二,名字: "+projectInfo.getProperty("author_name")+"信息:"+projectInfo.getProperty("project_info"));
}
}
测试结果:方式二,名字: 张三 信息:该项目主要是用于写一些demo
方式一:张三
方式一:该项目主要是用于写一些demo