Spring Container: Bean Dependency

Vivekanandan Sakthivelu
சுட சுட Code
2 min readAug 28, 2023
Image source: in28minutes

If a singleton scoped bean A colloborates with a prototype scoped bean B , how can bean A gets new instance of B or how can container provide bean A with new instance of B everytime it needs one ?

I’ve been asking this question lately to every candidate I interview, and to my disappointment, no one came up with the right way to do it. The given scenario is not just limited to prototype, whenever the bean of singleton scope collaborates with the non-singleton scoped bean.

Let's look at the snippet below, ReportGenerator class which generates reports of IReport type and is dependent on ContextHolder to generate a report successfully.

A new instance of UserContextHolder should be injected into ReportGenerator, every time any method is executed since we have defined the scope of UserContextHolder to be a prototype. Since the scope of ReportGenerator is a singleton; Spring Container gets only one chance to configure and assemble ReportGenerator during its creation even though the scope of its collaborator is a prototype.

But we need a new instance of ContextHolder every time the run method is executed !!

We can make Spring inject/return a new instance of ContextHolder every time the run method is called by either using AOP Proxy, Spring’s Method Injection, or Jarkata’s Provider.

Using Spring’s Method Injection,

Simply annotate a stub method with @Lookup which has a return type that you want during runtime. Additionally, @Lookup takes the qualified bean name as an argument, if you don't want the container to run into an ambiguous state. The arguments passed to the stub method will be intercepted and passed to getBean(beanName, …args) function of BeanFactory to retrieve a new instance of the bean

Usage of @Lookup

Under the hoods,

When a method is annotated with @Lookup, the implementation of BeanPostProcessor adds overrides method to BeanDefinition

All the calls to the method with @Lookup annotation will be intercepted to return the bean of the required type.

ref : org.springframework.beans.factory.support.CglibSubclassingInstantiationStrategy

If you found this to be useful, please leave a thumbs up :)

--

--

Vivekanandan Sakthivelu
சுட சுட Code

Conscious-being stuck in space-time continuum, who find solace in Kahlil Gibran writings. Sometimes I code,write;othertimes I enjoy melodrama of my own thoughts