【问题标题】:Spring @Configuration class needs to be autowiredSpring @Configuration 类需要自动装配
【发布时间】:2011-12-31 21:53:28
【问题描述】:

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

@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;
   }
}

【问题讨论】:

    标签: spring configuration autowired


    【解决方案1】:

    我不确定这是错误还是预期行为。有时它对我有用,有时没有。无论如何,还有另一种方法可以实现您想要的:

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

    【讨论】:

    • 谢谢,这对我有用。你有没有想过为什么会这样,或者自动装配一个类是否正确?
    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 2020-08-26
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 2017-09-07
    相关资源
    最近更新 更多