0

I am trying to use the @Value annotation on a variable to assign a value, but the value getting assigned is null. What am I doing wrong? I am using the java spring configuration using @Configuration. I am also using @PropertySource to point to a properties file.

@Configuration
@PropertySource("classpath:application.properties")
public class SpringConfiguration {
    @Value("${app_prop_1}") Integer aValue;

    @Bean
    public Integer getInteger() {
        return new Integer(aValue);  // throws NullPointerException
    }
}

The application.properties files is in the maven resources folder of project. It has following content:

app_prop_1=2000
Ali
  • 1,442
  • 1
  • 15
  • 29
  • Possible duplicate of [Spring @Value annotation always evaluating as null?](http://stackoverflow.com/questions/4130486/spring-value-annotation-always-evaluating-as-null) – Jens Schauder Sep 08 '16 at 06:16
  • Hint: according to the comments at https://jira.spring.io/browse/SPR-8539 it is not recommended to use `@Value` in `@Configuration` instead one should use `@Inject Environment env;` and then `env.getProperty("app_prop_")` – Ralph Sep 08 '16 at 06:49

1 Answers1

3

When you add @Value annotation, there is a need to add

//To resolve ${} in @Value
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
}

This will resolve the ${} expression.

Source

Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56
  • More details at: http://docs.spring.io/spring-framework/docs/4.2.x/javadoc-api/org/springframework/context/annotation/Configuration.html section "Using the @Value annotation" – Ralph Sep 08 '16 at 06:36