Spring MVC controller 读取配置文件

58 篇文章 0 订阅

用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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值