Spring @Configuration类需要自动装配

时间:2011-11-18 03:08:16

标签: spring configuration autowired

我已经创建了一个Spring @Configuration注释类,我想要将一个ResourceLoader自动装配到它,以便我可以在其中一个@Bean方法中使用它来查找由String给出的文件。当我运行应用程序并初始化上下文时,我得到一个访问自动装配字段的NPE,并且在调试模式下,它显示为空/未设置。我错在期待resourceLoader存在吗?我错误地断言配置bean的自动装配发生在其方法被调用之前?加载此bean的xml配置标记为< 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;
   }
}

1 个答案:

答案 0 :(得分:5)

我不确定这是一个错误还是预期的行为。有时它对我有用,有时却没有。无论如何,还有另一种方法可以达到你想要的效果:

public @Bean PropertiesFactoryBean appProperties(ResourceLoader resourceLoader) {
    // resourceLoader is injected correctly
    ...
}
相关问题