Spring MVC controller 读取配置文件

用Spring的MVC做开发有段时间里。天天打交道的就是各种的controller。

今天遇到一个问题,需要读取配置文件configure.properties,通过“注释”方式注入给controller。

spring的读取配置如下:

	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:config/configure.properties</value>
			</list>
		</property>
	</bean>

我的spring的XML配置文件如下:

spring-ctx-application.xml
spring-ctx-repository.xml
spring-mvc-servlet.xml

 我把PropertyPlaceholderConfigurer的XML配置放到了spring-ctx-application.xml里面。配置文件和controller的代码如下:

page.query.rownum=10
@Value("${page.query.rownum}")
	private String pageQueryRownum;
	
	
	public void setPageQueryRownum(String pageQueryRownum) {
		this.pageQueryRownum = pageQueryRownum;
	}

但是发现了一个问题,被注入的 pageQueryRownum 并没有打印出我期望的数字 10, 而是打印出来了${page.query.rownum}。让我困惑。

后来找到了问题,我把PropertyPlaceholderConfigurer的XML配置放到了spring-mvc-servlet.xml的xml中,问题就解决了。看了老外写的东西,才知道,这是不同的spring context,才造成配置在 spring-ctx-application.xml的配置信息无法读取到。而我的springMVC的配置信息都在spring-mvc-servlet.xml中。为了让controller读取到配置文件,需要把PropertyPlaceholderConfigurer的XML配置到同样的context的spring-mvc-servlet.xml中,问题就解决了。

参考:

http://stackoverflow.com/questions/5275724/spring-3-0-5-doesnt-evaluate-value-annotation-from-properties

http://stackoverflow.com/questions/11890544/spring-value-annotation-in-controller-class-not-evaluating-to-value-inside-pro

猜你喜欢

转载自kanpiaoxue.iteye.com/blog/1989026