Spring 3.0.5 不会从属性评估 @Value 注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5275724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:22:14  来源:igfitidea点击:

Spring 3.0.5 doesn't evaluate @Value annotation from properties

springframeworkspropertiesautowired

提问by Alex Yarmula

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

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

  • config.properties:

    username=myusername
    
  • main-components.xml:

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

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

    username=myusername
    
  • main-components.xml

    <context:property-placeholder location="classpath:config.properties" />
    
  • 我的课:

    @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 @Autowiredbut it didn't help.

结果,用户名被设置为字面意思"${username}",所以表达式不会被解析。我对这个类的其他自动连接依赖被设置,并且 Spring 不会抛出任何异常。我也尝试添加,@Autowired但没有帮助。

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

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

<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

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

采纳答案by Alex Yarmula

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

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

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

你是对的。我<context:property-placeholder>从 定义的上下文转移ContextLoaderListener到 servlet 上下文。现在我的价值观得到解析。非常感谢!- 亚历克斯