1.测试类
- 要求在xml文件中创建bean, 并通过引入外部属性文件的方式注入属性值.
User 类
package com.limi.test;
public class User {
private String name;
private Integer age;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试类MyTest
package com.limi.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test1(){
//1.加载bean的xml文件, 以src为根目录
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
//2.获取配置的对象, 参数1:bean的id值, 参数2: 类名.class
User user1 = context.getBean("User", User.class);
//3.使用对象
System.out.println("user1:"+user1);
}
}
2.xml文件的编写
- 第一步:引入context命名空间
- 第二步:引入外部属性文件
- 第三步:引用外部属性文件中的属性值
bean1.xml
bean1.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: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命名空间-->
<!-- 需要修改beans标签, 引入context命名空间, 上面的灰色部分即为新增内容-->
<!-- 第二步:引入外部属性文件-->
<!--引入外部属性文件user.properties-->
<context:property-placeholder location="user.properties"></context:property-placeholder>
<!--id是唯一标识, class是全类名 -->
<bean id="User" class="com.limi.test.User">
<!--第三步:引用外部属性文件中的属性值-->
<!--使用方法${外部属性名}-->
<property name="name" value="${user.name}"></property>
<property name="age" value="${user.age}"></property>
</bean>
</beans>
3.测试结果
可以看到成功地通过外部属性文件为bean注入属性值.