Spring framework可以到此处下载:http://maxwoods.ctfile.com/u/758954/11098882,这里使用Spring 4。
新建一个j2ee的web工程,将压缩包中对应的jar包放到WEB工程的lib子目录中,如/WebContent/WEB-INF/lib。
修改web.xml文件,在web-app节点加入对应配置:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/*.xml
</param-value>
</context-param>
spring为源码目录中放置 spring的配置文件的子目录。
Spring的配置文件中,可以通过<context:property-placeholder>标记来加载.properties配置文件,并通过file-encoding属性来指定字符编码。
还可以通过org.springframework.beans.factory.config.PropertyPlaceholderConfigurer来加载属性文件。
<?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-4.1.xsd">
<context:property-placeholder location="classpath*:spring.properties" file-encoding="UTF-8"/>
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="fileEncoding" value="UTF-8"/>
<property name="locations">
<list>
<value>classpath*:spring.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
<property name="locations">
<list>
<value>classpath:spring.properties</value>
</list>
</property>
</bean>
</beans>
在Servlet中,可以通过以下代码访问配置文件中的Properties:
ApplicationContext context= WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
Properties property=(Properties)context.getBean("configProperties");