32

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

AdrieanKhisbe
  • 3,899
  • 8
  • 37
  • 45
Alex Yarmula
  • 10,477
  • 5
  • 33
  • 32
  • 18
    Are you sure you have `` in the same application context as your `MyClass` bean (not in the parent context)? – axtavt Mar 11 '11 at 16:47
  • You're right. I moved from context defined by ContextLoaderListener to servlet context. Now my values get parsed. Thanks a lot! – Alex Yarmula Mar 11 '11 at 16:54
  • 1
    quite a useful thing to do here is to set ignore-unresolvable-placeholders to false - thus the application will fail if it cannot resolve place holders - which is what your problem was – Michael Wiles Aug 10 '12 at 11:22
  • Found this answer after many hours of wondering why my @Value annotations weren't working :( As mentioned in [other post](http://stackoverflow.com/questions/11890544/spring-value-annotation-in-controller-class-not-evaluating-to-value-inside-pro) BeanPostProcessor is not shared accross containers even in same hierachy – Mike R Sep 09 '13 at 19:26
  • You can @Autowire Environment and then environment.getProperty("name"). See http://stackoverflow.com/a/15562319/632293 – jediz Apr 01 '16 at 16:00

1 Answers1

22

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

ptikobj
  • 2,690
  • 7
  • 39
  • 64
Alex Yarmula
  • 10,477
  • 5
  • 33
  • 32