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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With