Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: how to initialize related lazy beans after main 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 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?

like image 596
mitallast Avatar asked Oct 19 '22 23:10

mitallast


1 Answers

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.

like image 93
Xstian Avatar answered Oct 22 '22 12:10

Xstian