Issue
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?
Solution
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.
Answered By - Xstian
Answer Checked By - Gilberto Lyons (JavaFixing Admin)