60

I've been breaking my head on this one. Not sure what I am missing. I am unable to get the @Value annotations to work in a pure java configured spring app(non web)

@Configuration
@PropertySource("classpath:app.properties")
public class Config {
    @Value("${my.prop}") 
    String name;

    @Autowired
    Environment env;

    @Bean(name = "myBean", initMethod = "print")
    public MyBean getMyBean(){
         MyBean myBean = new MyBean();
         myBean.setName(name);
         System.out.println(env.getProperty("my.prop"));
         return myBean;
    }
}

The property file just contains my.prop=avalue The bean is as follows:

public class MyBean {
    String name;
    public void print() {
        System.out.println("Name: " + name);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

The environment variable prints the value properly, the @Value does not.
avalue
Name: ${my.prop}

The main class just initializes the context.

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);

However if I use

@ImportResource("classpath:property-config.xml")

with this snippet

<context:property-placeholder location="app.properties" />

then it works fine. Of course now the enviroment returns null.

1 Answer 1

110

Add the following bean declaration in your Config class

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

In order for @Value annotations to work PropertySourcesPlaceholderConfigurer should be registered. It is done automatically when using <context:property-placeholder> in XML, but should be registered as a static @Bean when using @Configuration.

See @PropertySource documentation and this Spring Framework Jira issue.

Sign up to request clarification or add additional context in comments.

3 Comments

This worked great! The spring doc @Configuration misses this out. Leading to all this confusion
+1 - Embarrassingly, I always seem to forget this when starting a new project, and I find this answer each time.
Registering the bean as "static" is the key to me. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.