我有一个使用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}记录在我的日志文件中。我没有得到它的价值。同样,如果我在属性文件中放置一个整数/浮点数,则会收到一条错误消息,指出无法将其转换为整数/浮点数。我是否缺少任何配置?

最佳答案

这样做的原因是因为propertyplaceholder configurer是BeanFactoryPostProcessor,它仅处理在配置propertyplaceholder的上下文中定义的bean。在Web应用程序中,通常存在上下文的层次结构,如here所述。因此,您需要在适当的位置进行声明。

10-07 13:21
查看更多