Spring 3.0.5 doesn't evaluate @Value annotation from properties

拥有回忆 提交于 2019-12-17 15:47:16

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/5275724/spring-3-0-5-doesnt-evaluate-value-annotation-from-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!