Issue
I am trying to create Spring beans using only annotations. I am not able to load values for my @Bean class from properties file.
Here is my code:
This is my main class
public class AnnotationDI {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ConfigurationProvider.class);
ApplicationProperties properties = (ApplicationProperties)context.getBean(ApplicationProperties.class);
System.out.println(properties);
}}
Configuration class
@Configuration
public class ConfigurationProvider {
private ApplicationProperties m_applicationProperties;
@Bean
public ApplicationProperties getApplicationProperties() {
return new ApplicationProperties();
}
}
Bean class
@PropertySource(value = { "classpath:application.properties" })
public class ApplicationProperties {
@Value("${longThreadCount}")
private String m_longProcessThread;
@Value("${routeTimeout}")
private String m_routeTimeout;
@Value("${updateDirectoryPath}")
private String m_updateDirectoryPath;
public String getLongProcessThread() {
return m_longProcessThread;
}
@Override
public String toString() {
return "ApplicationProperties [m_longProcessThread=" +m_longProcessThread"]";
}
}
when i run this program, I get following output
m_longProcessThread=${longThreadCount}
Any idea what am i doing wrong?
Solution
To be able to have @Value
with placeholders resolved you need to register a PropertySourcesPlaceholderConfigurer
. As this is a BeanFactoryPostProcessor
it needs to be registered as a static
bean so that it can be detected early on in the process.
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Answered By - M. Deinum