Spring 3.0.5不会评估属性的@Value注释 [英] Spring 3.0.5 doesn't evaluate @Value annotation from properties

查看:119
本文介绍了Spring 3.0.5不会评估属性的@Value注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将属性自动连接到 Spring 3.0.5.RELEASE 中的bean,我使用:


  • config.properties

      username = myusername 


  • main-components.xml

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


  • MyClass:

    <$ p $ @Service
    public class MyClass {

    @Value($ {username})
    private String username;
    ...
    }




因此,用户名被设置为 $ {username},所以表达式不会被解析。我对这个类的其他自动连线依赖性得到了设置,并且Spring不会抛出任何异常。我也尝试添加 @Autowired 但它没有帮助。



如果我将属性解析为单独的bean然后使用 @Autowired + @Qualifier ,它可以工作:

 < bean id =usernameclass =java.lang.String> 
< constructor-arg value =$ {username}/>
< / bean>

如何使用 @Value ?也许我需要包含一些我没有的Spring依赖项?谢谢

解决方案

找到问题所在。复制/粘贴评论:



您确定您的< context:property-placeholder> 应用程序上下文作为你的MyClass bean(不在父上下文中)? - axtavt



你说得对。我从 ContextLoaderListener 定义的上下文中将< context:property-placeholder> 移到了servlet上下文中。现在我的值被解析。非常感谢! - alex


Trying to auto-wire properties to a bean in Spring 3.0.5.RELEASE, I'm using:

  • config.properties:

    username=myusername
    

  • main-components.xml:

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

  • MyClass:

    @Service
    public class MyClass {
    
        @Value("${username}")
        private String username;
        ...
    }
    

As a result, username gets set to literally "${username}", so the expression doesn't get parsed. My other auto-wired dependencies on this class get set, and Spring doesn't throw any exception. I also tried to add @Autowired but it didn't help.

If I parse properties to a separate bean and then use @Autowired + @Qualifier, it works:

<bean id="username" class="java.lang.String">
    <constructor-arg value="${username}"/>
</bean>

Any ideas how to use just @Value? Maybe I need to include some Spring dependency that I haven't? Thank you

解决方案

Found what the issue was. Copy/paste from comments:

Are you sure you have <context:property-placeholder> in the same application context as your MyClass bean (not in the parent context)? – axtavt

You're right. I moved <context:property-placeholder> from the context defined by the ContextLoaderListener to the servlet context. Now my values get parsed. Thanks a lot! - alex

这篇关于Spring 3.0.5不会评估属性的@Value注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆