Spring @Autowired不适用于急切初始化的bean

时间:2013-10-05 08:25:38

标签: java spring dependency-injection annotations spring-3

我正在尝试编写面向服务的应用程序。

我被称为memory被定义为:

package com.example.assets;

//imports ignored

@Resource
public class Memory {
}

我有一个名为memoryHandler的服务定义如下:

package com.example.service;

//imports ignored

@Service
public class MemoryHandler {

    @Autowired
    private Memory memory;

    public void execute() {
        //do something with memory
    }
}

还有另一个类,即BeanFactoryPostProcessor

package com.example.service;

//imports ignored

@Component
public class PostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        beanFactory.getBeansOfType(MemoryHandler.class, false, true);
    }
}

过早地查找bean memoryHandler,让它实例化但不是自动装配的。但是,我希望bean在工厂提取之前自动装配。

在我的主要课程中,我写道:

package com.example.service;

//imports ignored

public class Main {

    public static void main(String[] args) {
        final ApplicationContext context = new ClassPathXmlApplicationContext("/context.xml");
        context.getBean(MemoryHandler.class).execute();
    }

}

我在使用内存的行上获得NullPointerException。我用setter注入替换了上面的声明,并且在跟踪时意识到注入永远不会发生。

我已将这两个组件的注释更改为ServiceRepositoryComponent,并尝试将Autowired替换为Resource无效。

我在这里缺少什么?我已经阅读了我在寻找答案时出现的所有问题,但没有一个能帮助我(我得到了关于在那里使用Resouce注释的提示)。

毋庸置疑,我没有错过我的bean的注释配置:

<context:annotation-config/>
<context:component-scan base-package="com.example"/>

此外,当在XML配置文件中定义自动装配的bean时,自动装配工作正常,而不是通过注释。

我正在使用Spring 3.2.3.RELEASE。

1 个答案:

答案 0 :(得分:1)

更改PostProcessor的实现是关键:

而不是:

public class PostProcessor implements BeanFactoryPostProcessor {

我必须写:

public class PostProcessor implements ApplicationContextAware {

这可以确保在后处理之前完全填充上下文,在我的情况下工作正常。但我想知道是否有另一种方法可以使用通常的BeanFactoryPostProcessor界面?