31

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

  • config.properties

    username=myusername
    
  • main-components.xml

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

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

结果,用户名被设置为字面意思 "${username}",因此表达式不会被解析。我对此类的其他自动关联依赖项已设置,并且 Spring 不会引发任何异常。我也尝试添加@Autowired,但没有帮助。

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

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

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

4

1 回答 1

22

发现了问题所在。从评论中复制/粘贴:

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

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

于 2011-03-11T16:55:14.280 回答