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

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 initializing the application context, there are no instances of this beans. When a resource bean is created by the application context (for example, applicationContext.getBean (Resource.class)), instances of @CustomProcessor are not marked with beans.

When creating a bean resource, you must create beans with @CustomProcessor. How to do it?

Updated: One of the ugly solutions found - use an empty autoinstaller:

 @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 is a more elegant way?

+5
source share
1 answer

You must create a marker interface like CustomProcessor

 public interface CustomProcessor{ } 

later, each ResourceProcessor must implement the interface above.

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

The resource must implement 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 the Resource bean is referenced, a postconstruct begins, which initializes all the bean that implements the CustomProcessor interface.

+3
source

Source: https://habr.com/ru/post/1206344/


All Articles