Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

frameworks - Spring 3.0.5 doesn't evaluate @Value annotation from properties

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...