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

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

问题描述

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

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;
        ...
    }
    

  • 因此,username 被设置为 literally "${username}",因此表达式不会被解析.我在这个类上的其他自动连接依赖被设置,并且 Spring 不会抛出任何异常.我也尝试添加 @Autowired 但它没有帮助.

    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.

    如果我将属性解析为一个单独的 bean,然后使用 @Autowired + @Qualifier,它会起作用:

    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>
    

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

    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:

    您确定在与 MyClass bean 相同的应用程序上下文中(不在父上下文中)有 吗?– axtavt

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

    你说得对.我将 从由 ContextLoaderListener 定义的上下文移动到 servlet 上下文.现在我的价值观得到解析.非常感谢!- 亚历克斯

    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天全站免登陆