\n\n
@Configuration\npublic class ClientConfig {\n\n @Autowired\n private ResourceLoader resourceLoader;\n\n public @Bean\n String configHome() {\n return System.getProperty(\"CONFIG_HOME\");\n }\n\n public @Bean\n PropertiesFactoryBean appProperties() {\n String location = \"file:\" + configHome() + \"/conf/webservice.properties\";\n PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();\n factoryBean.setLocation(resourceLoader.getResource(location));\n\n return factoryBean;\n }\n}\n
\n","author":{"@type":"Person","name":"Kai"},"upvoteCount":3,"answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"I'm not sure whether this is a bug or is the expected behavior. Sometimes it worked for me, sometimes didn't. Anyway, there is another way of achieving what you want:
\n\npublic @Bean PropertiesFactoryBean appProperties(ResourceLoader resourceLoader) {\n // resourceLoader is injected correctly\n ...\n}\n
\n","author":{"@type":"Person","name":"sinuhepop"},"upvoteCount":6}}}Reputation: 2205
I've created a Spring @Configuration annotated class and I want to autowire a ResourceLoader to it so that I can use it in one of the @Bean methods to lookup a file given by a String. When I am running the app and initialising the context I get a NPE accessing the autowired field, and in debug mode it is shown as being null/not set. Am I wrong expecting the resourceLoader to be present? Am I wrong asserting the autowiring of the Configuration bean happens before its methods get called? The xml configuration loading this bean is tagged with <context:annotation-config/>
@Configuration
public class ClientConfig {
@Autowired
private ResourceLoader resourceLoader;
public @Bean
String configHome() {
return System.getProperty("CONFIG_HOME");
}
public @Bean
PropertiesFactoryBean appProperties() {
String location = "file:" + configHome() + "/conf/webservice.properties";
PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
factoryBean.setLocation(resourceLoader.getResource(location));
return factoryBean;
}
}
Upvotes: 3
Views: 2074
Reputation: 20336
I'm not sure whether this is a bug or is the expected behavior. Sometimes it worked for me, sometimes didn't. Anyway, there is another way of achieving what you want:
public @Bean PropertiesFactoryBean appProperties(ResourceLoader resourceLoader) {
// resourceLoader is injected correctly
...
}
Upvotes: 6