@Value not working in Spring @Configuration

Viewed 11095

Need help, where is the issue?

I have a configuration class which is loading properties as

WebConfig.java

@Configuration
@PropertySource(value={"classpath:application.properties"})
class WebConfig extends WebMvcConfigurerAdapter{

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

I have another configuration class where I am trying to use the properties as

MyServerConfig.java

@Configuration
class MyServerConfig {

    @Value("${server.url}")
    private String url;
...
}

application.properties

server.url=http://localhost:8080/test/abc

But getting:

java.lang.IllegalArgumentException: Could not resolve placeholder 'server.url'.

Don't know what is missing here? Any thoughts?

2 Answers

Use the @PropertyScan annotation in the class where a certain property will be used:

@Configuration
@PropertyScan("classpath:application.properties")
class MyServerConfig {

    @Value( "${server.url}" )
    private String url;
}

For getting the values for your @Value variables, the application.properties is not needed to be configured in any special way because this file is always scanned. So remove the @PropertySource annotation and PropertySourcesPlaceholderConfigurer bean.

These are used if you want to add other .properties files (e.g. constants.properties, db-config.properties).

So just remove those and try to run your application again

Very important:

  1. Make sure you scan the class that uses the @Value annotation (If your BootApplication is in some package instead of the 'main' package, add the proper @SpringBootApplication(scanBasePackages = { "com.my.project" }) annotation).

  2. Make sure your application.properties is on your classpath.

Bonus If you are using spring profiles (e.g: prod, dev), you can also have application-prod.properties and application-dev.properties files that will be scanned and included depending on which profile you are running.

Related