Kai
Kai

Reputation: 2205

Spring @Configuration class needs to be autowired

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

Answers (1)

sinuhepop
sinuhepop

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

Related Questions