这里只提供一种可实现方法,其它方法不讨论。
我们使用PropertyPlaceholderConfigurer方法为例,涉及四个文件:
1:properties文件,这里是config.properties,放置在properties文件常放置的地方,即src/main/resources目录下
2:一个存放properties配置文件属性的Bean,这里是HelloWorldBean.java
3:配置文件,这里是config.xml,由于我们要使用ClassPathXmlApplicationContext读取这个配置文件,因此这个文件要放置在WEB-INF/classes目录下才会被ClassPathXmlApplicationContext找到
4:读取配置的Controller
下面对每个文件的具体内容做详细解释:
config.properties
HelloWorldBean.hello=Hello Properties!!!
其中前面的HelloWorldBean.bean可以随便取名,不过会和后面的配置一一对应,我们在后面会看到,Hello Properties!!!是属性值
HelloWorldBean.java
package com.yunzu.movierecommend;
public class HelloWorldBean {
private String helloworld;
/**
* @return the helloworld
*/
public String getHelloworld() {
return helloworld;
}
/**
* @param helloworld the helloworld to set
*/
public void setHelloworld(String helloworld) {
this.helloworld = helloworld;
}
}
这里的类名HelloWorldBean和成员变量helloworld在下面的config.xml中都有对应设置
config.xml
<?xml version= "1.0" encoding= "UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config.properties" />
</bean>
<bean id="HelloWorld" class="com.yunzu.movierecommend.HelloWorldBean">
<property name="helloworld" value= "${HelloWorldBean.hello}" />
</bean>
</beans>
注意上面的配置中:
<property name="location" value="classpath:config.properties" />
指明properties文件的名称
<bean id="HelloWorld" class="com.yunzu.movierecommend.HelloWorldBean">
<property name="helloworld" value= "${HelloWorldBean.hello}" />
</bean>
id是自己取的一个名字,什么都是可以的,class必须是对应的Bean类名,property的name必须对应Bean中对应定义的成员变量,这里是helloworld,value对应properties文件对应的定义
Controller中对应的调用代码
private String HELLO_WORLD = "aaaasdf___aaasf";
@PostConstruct
public void init()
{
ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
HelloWorldBean hwb = (HelloWorldBean)context.getBean("HelloWorld");
HELLO_WORLD = hwb.getHelloworld();
System.out.println( "HELLO_WORLD is: " + HELLO_WORLD );
}
其中:
ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
上面代码打开WEB-INF/classes目录下的config.xml文件
HelloWorldBean hwb = (HelloWorldBean)context.getBean("HelloWorld");
上面的代码获得id为HelloWorld的Bean,properties文件中的值会设置到Bean中,可以通过get方法获得
有以上这些代码,就可以测试了