先看一个最简单的spring管理一个bean的例子
定义一个Person类
package springresearch;
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
在spring的applicationContext.xml最后进行bean管理和属性注入
<bean id="person" class="springresearch.Person">
<property name="name" value="liuqi" />
<property name="age" value="21" />
</bean>
最好的办法就是将这些属性单独拿出来放到配置文件中,方便以后的修改和阅读
我们定义一个config.properties文件
name=liuqi
age=21
然而spring作为一种框架,提供了大量的现成类来集成管理各种技术,只需要我们将这些类配置出来即可。spring中管理配置文件的类就是PropertyPlaceholderConfigurer。
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config.properties" />
<property name="fileEncoding" value="utf-8" />
</bean>
这里的 classpath关键词在下一篇文章做详细解析
然后我们在spring中配置其他bean时就可以使用config中的属性了
<bean id="person" class="springresearch.Person">
<property name="name" value="${name}" />
<property name="age" value="${age}" />
</bean>
最终结果
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new FileSystemXmlApplicationContext(
"classpath:applicationContext.xml");
Person person = (Person) ac.getBean("person");
System.out.println(person.getName());
System.out.println(person.getAge());
}
}
得出的结果一样
一般来说 配置数据库、配置日志文件都需要这样写,本文只是简单地讲解了一下spring中加载配置文件的方式,接下来的文章我会详细研究PropertyPlaceholderConfigurer的源代码以及深入理解,欢迎关注。