【发布时间】:2014-07-13 15:20:09
【问题描述】:
我有一个使用 Spring MVC 的 Web 应用程序。我在sample.properties 文件中定义了几个常量。 spring-servlet 是为我的应用程序中的所有 url 初始化的 servlet。 spring-servlet:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<context:property-placeholder location="classpath:sample.properties"/>
</beans>
在我的一个 java 类中,我访问如下属性之一的值:
package com.sample;
import com.google.gson.JsonArray;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Validator {
@Value("${credit}")
String credits;
private static final Logger LOG = Logger.getLogger(Validator.class);
public void checkRating() {
LOG.debug(credits);
}
}
sample.properties:
credit=[{"duration":15,"credit":10},{"duration":30,"credit":20}]
当从控制器调用 Validator 时,它只会在我的日志文件中将其记录为 ${credit}。我不明白它的价值。同样,如果我在属性文件中放入一个整数/浮点数,我会收到一条错误消息,指出它不能转换为整数/浮点数。我是否缺少任何配置?
【问题讨论】:
-
请再次确认properties文件是放在classpath下,直接在bin或build文件夹下。
-
这是一个基于 gradle 的项目。我把它放在 src/main/resources 下。它也在构建目录下(resources/main/sample.properties)。
-
我不确定这是问题所在还是您正在运行的 Spring 版本。但是请尝试将 XSD 更新为正确的版本。它现在使用
3.0,这可能不是要使用的正确版本。 -
我现在将其更改为 3.2,因为我使用的是 3.2.4.RELEASE。但仍然没有运气:(
-
我通过将 context:property-placeholder 放置在 applicationContext.xml 而不是 spring-servlet 来修复它。
标签: java spring spring-mvc