Reputation: 4156
I am trying to create a class that contains values stored in property files in spring boot
so far I have the sample.properties file with the property "source.Ip" set.
The class is as follows:
@PropertySource({"classpath:sample.properties"})
@Configuration
@Component
public class PropertyLoader {
@Value("${source.Ip}")
private String sourceIp;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public String getSourceIP(){
return sourceIp;
}
}
The property file is directly under src/main/resources which is a source folder.
However I get a :
java.lang.IllegalArgumentException: Could not resolve placeholder 'source.Ip' in string value "${source.Ip}"
As for my main class it is simply as follows:
@Configuration
@EnableAutoConfiguration
public class AppStarter {
public static void main(String args[]){
System.out.println(SpringApplication.run(AppStarter.class, args).getBean(PropertyLoader.class).getSourceIP());
}
@Bean
public PropertyLoader propertyLoader(){
return new PropertyLoader();
}
}
sample.properties content:
source.Ip=127.0.0.1
Upvotes: 0
Views: 1441
Reputation: 10679
In order to resolve ${...}
placeholders in <bean>
definitions or @Value
annotations using properties from a PropertySource
, you must register a PropertySourcesPlaceholderConfigurer
. This happens automatically when using <context:property-placeholder>
in XML
, but must be explicitly registered using a static @Bean
method when using @Configuration
classes.
The method must be static for the PropertySourcesPlaceholderConfigurer
Because BeanFactoryPostProcessor (BFPP)
objects must be instantiated very early in the container lifecycle, they can interfere with processing of annotations such as @Autowired
, @Value
, and @PostConstruct
within @Configuration
classes.
Adding this to your application class should do the trick :
@Bean
public static PropertySourcesPlaceholderConfigurer pspc() {
PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
return pspc;
}
From the PropertySource documentation.
EDIT
Have you try to
PropertySourcesPlaceholderConfigurer
in the AppStarter
class.PropertySource
annotation to the AppStarter
class.Configuration
annotation on the PropertyLoader
.The problem is probably related to the fact that the PropertyLoader
is a component and a configuration class.
Upvotes: 2