Spring MVC:@Value注释以获取 *.properties 文件中定义的 int 值



我有一个config.properties文件:

limit=10

My springmvc-servlet.xml:

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

这是我的控制器类:

@Controller
@RequestMapping(...)
public class Test extends BaseController
{
    @Value("${limit}") Integer limit;   // This doesn't work
    @Value("#{T(java.lang.Integer).parseInt(${limit})}") Integer limit;   // This also doesn't work
    @RequestMapping(...)
    @ResponseBody
    public String session()
    {
        return String.valueOf(limit);
    }
}

错误消息是:

Error creating bean with name 'test': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: java.lang.Integer **.Test.limit; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1043E:(pos 31): Unexpected token. Expected 'rparen())' but was 'lcurly({)'

有什么想法吗?

尝试以下操作:

@Value("#{config.limit}") Integer limit;

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/new-in-3.html 的文档

给出的例子有:

@Repository 
public class RewardsTestDatabase {
    @Value("#{systemProperties.databaseName}")
    public void setDatabaseName(String dbName) { … }
    @Value("#{strategyBean.databaseKeyGenerator}")
    public void setKeyGenerator(KeyGenerator kg) { … }
}

更新:我测试过并遇到了同样的问题。按照如何将属性值注入注释配置的弹簧 mvc 3.0 控制器中的说明弄清楚了

在你的代码中:

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

类路径是指战争文件中的 WEB-INF/类路径。那么你在 WEB-INF/类中有配置文件夹吗?

如果是,则使用基于 xml 的配置进行检查,如下所示:

<bean id="dataSource" class="org.tempuri.DataBeanClass">
    <property name="url" value="${url}"></property>
</bean>

如果仍然出现错误,则属性文件加载肯定存在问题。

试试这个:@Value("#{new Integer('${limit}')}")

<context:property-placeholder location="config/config.properties" />

最新更新