属性文件
新建一个属性文件,属性文件后缀为 .properties
的文件,文件放在 src 文件夹下
pen1.id=1
pen1.brand=picasso
pen1.price=163.05
pen2.id=2
pen2.brand=picasso
pen2.price=760.45
pen3.id=3
pen3.brand=hero
pen3.price=45.50
xml 配置文件
若要使用 Spring 配置文件读取属性文件的内容,第一步就想要将属性文件加载上下文中,因此我们使用 context:property-placeholder
标签将属性文件加载到上下文中,其中 location 指定属性文件的位置,一般以 src 文件夹为基准。 当需要在 xml 使用到属性文件中的某些值时可以直接使用 ${}
将需要的变量引出即可。
<?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:c="http://www.springframework.org/schema/c"
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-4.3.xsd">
<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:PenData.properties"/>
<bean id="pen1" class="cn.edu.stu.Demo5.Pen">
<property name="id" value="${pen1.id}"></property>
<property name="brand" value="${pen1.brand}"></property>
<property name="price" value="${pen1.price}"></property>
</bean>
<bean id="pen2" class="cn.edu.stu.Demo5.Pen">
<property name="id" value="${pen2.id}"></property>
<property name="brand" value="${pen2.brand}"></property>
<property name="price" value="${pen2.price}"></property>
</bean>
</beans>
测试
@Test
public void Test1() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("BeanDemo5Context.xml");
Pen pen1 = (Pen)ctx.getBean("pen1");
Pen pen2 = (Pen)ctx.getBean("pen2");
System.out.println(pen1);
System.out.println(pen2);
}
运行结果
Create a new Pen Bean
Create a new Pen Bean
Pen [id=1, brand=picasso, price=163.05]
Pen [id=2, brand=picasso, price=760.45]