获得 Properties 文件的值
1、Spring 配置文件支持通过 Properties 文件的 Key 获得对应的值。实现该功能是通过 PropertySourcesPlaceholderConfigurer 指定 Properties 的路径,再通过 ${Key} 来获得 Properties 文件对应 Key 的值。
示例代码:
① 导入包:
② 编写一个普通的 CustomerService 类:
1 package cn.mgy.service; 2 3 import java.util.Date; 4 5 public class CustomerService { 6 7 private int age; 8 private String name; 9 private Date birthDate; 10 11 public void setAge(int age) { 12 this.age = age; 13 } 14 15 public void setName(String name) { 16 this.name = name; 17 } 18 19 public void setBirthDate(Date birthDate) { 20 this.birthDate = birthDate; 21 } 22 23 public void reigster(){ 24 System.out.println("姓名:"+name); 25 System.out.println("年龄:"+age); 26 System.out.println("生日:"+birthDate); 27 } 28 }
③ 编写 Properties 文件键值对:
注意:默认必须是 ISO-8859-1 编码
customer.age = 20 customer.name =\u5F20\u4E09 |
如果需要其他编码,需要在 Spring 配置文件里面设置:
1 <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> 2 <!-- 指定加载的Properties的文件路径 --> 3 <property name="locations" value="classpath:sys.properties"></property> 4 <!-- 注意:默认是ISO-8859-1编号,如果要使用其他编码,需要设置 --> 5 <property name="fileEncoding" value="UTF-8"></property> 6 </bean>
④ 编写配置文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "> 5 <bean name="now" class="java.util.Date"></bean> 6 <bean name="customerService" class="cn.mgy.service.CustomerService"> 7 <!-- 一个property标签匹配一个set方法 --> 8 <property name="name" value="${customer.name}"></property> 9 <property name="age" value="${customer.age}"></property> 10 <property name="birthDate" ref="now"></property> 11 </bean> 12 13 <!-- 配置指定Properties的路径 --> 14 <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"> 15 <property name="locations" value="classpath:customer.properties"></property> 16 </bean> 17 </beans>
⑤ 测试:
1 package cn.mgy.test; 2 3 import org.springframework.context.support.ClassPathXmlApplicationContext; 4 5 import cn.mgy.service.CustomerService; 6 7 public class CustomerServiceTest { 8 9 public static void main(String[] args) { 10 ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("bean.xml"); 11 12 CustomerService customerService = context.getBean("customerService",CustomerService.class); 13 customerService.reigster(); 14 context.close(); 15 } 16 17 }