Spring: how to initialize related lazy beans after main bean creation

早过忘川 提交于 2020-01-03 13:57:26

问题


I have code with lazy initialized beans:

@Component @Lazy
class Resource {...}

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

After initialize application context, there's no instances of this beans. When bean Resource is created by application context (as example, applicationContext.getBean(Resource.class)), no instances of @CustomProcessor marked beans.

It's need to create beans with @CustomProcessor when created Resource bean. How to do it?

Updated: One of ugly solution found - use empty autowired setter:

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

Another ugly solution with bean BeanPostProcessor (so magic!)

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

Maybe there's a more elegant way?


回答1:


You must create a marker interface like CustomProcessor

public interface CustomProcessor{

}

later each ResourceProcessor must be implements above interface

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

Resource must implements 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;   
    }

}

When Resource bean will be referenced starts the postconstruct that initialize all bean that implements CustomProcessor interface.



来源:https://stackoverflow.com/questions/26780957/spring-how-to-initialize-related-lazy-beans-after-main-bean-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!