Spring:如何在主bean创建后初始化相关的懒豆

时间:2014-11-06 13:41:04

标签: java spring spring-bean

我有懒惰初始化bean的代码:

@Component @Lazy
class Resource {...}

@Component @Lazy @CustomProcessor
class ResourceProcessorFoo{
    @Autowired
    public ResourceProcessor(Resource resource) {...}
}
@Component @Lazy @CustomProcessor
class ResourceProcessorBar{
    @Autowired
    public ResourceProcessor(Resource resource) {...}
}

初始化应用程序上下文后,没有此bean的实例。当bean资源由应用程序上下文创建时(例如,applicationContext.getBean(Resource.class)),没有@CustomProcessor实例标记bean。

在创建Resource bean时,需要使用@CustomProcessor创建bean。怎么做?

更新: 找到一个丑陋的解决方案 - 使用空的自动装配器:

@Autowired
public void setProcessors(List<ResourceProcessor> processor){}

Bean BeanPostProcessor的另一个丑陋的解决方案(太神奇了!)

@Component
class CustomProcessor implements BeanPostProcessor{
    public postProcessBeforeInitialization(Object bean, String beanName) {
        if(bean instanceof Resource){
            applicationContext.getBeansWithAnnotation(CustomProcessor.class);
        }
    }
}

也许有更优雅的方式?

1 个答案:

答案 0 :(得分:3)

您必须创建一个标记界面,如CustomProcessor

public interface CustomProcessor{

}

以后每个ResourceProcessor必须在接口

之上实现
@Component @Lazy 
class ResourceProcessorFoo implements CustomProcessor{
    @Autowired
    public ResourceProcessor(Resource resource) {...}
}
@Component @Lazy 
class ResourceProcessorBar implements CustomProcessor{
    @Autowired
    public ResourceProcessor(Resource resource) {...}
}

资源必须实现ApplicationContextAware

@Component
@Lazy
public class Resource implements ApplicationContextAware{

    private ApplicationContext applicationContext;

    @PostConstruct
    public void post(){
        applicationContext.getBeansOfType(CustomProcessor.class);
    }

    public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
        this.applicationContext = applicationContext;   
    }

}

当引用Resource bean时,启动postconstruct,初始化实现CustomProcessor接口的所有bean。