Prev Next

Spring / Spring Beans

Explain the Scope Injection problem and provide a solution to fix it.

Injecting longer-lived into shorter-lived: This works as expected. For example, injecting a singleton bean (which is created once for the entire application) into a prototype bean (new instance for each request) means all prototype instances share the single singleton instance. This is common for stateless dependencies.

Injecting shorter-lived into longer-lived (the "scoped bean injection problem"): If you directly inject a prototype bean into a singleton bean using @Autowired, only one instance of the prototype bean is created when the singleton bean is initialized and that same instance is reused throughout the application's life. This defeats the purpose of the prototype scope.

Solutions for the "Scoped Bean Injection Problem":

To ensure a new instance of a shorter-lived bean is provided on each access within a longer-lived bean, use the following mechanisms:

  • @Lookup method injection: This is the cleanest way for prototype beans. Spring overrides the annotated method at runtime to return a new instance of the requested bean whenever the method is called.
    @Component
    @Scope("singleton")
    public abstract class SingletonBean {
        @Lookup
        public abstract PrototypeBean getPrototypeBean();
        // ...
    }
    
  • ObjectFactory or Provider injection: Injecting ObjectFactory or Provider (from javax.inject) allows you to explicitly call a getObject() or get() method to request a new instance whenever needed.
    @Component
    @Scope("singleton")
    public class SingletonBean {
        @Autowired
        private ObjectFactory<PrototypeBean> prototypeBeanFactory;
    
        public void doSomething() {
            PrototypeBean prototypeBean = prototypeBeanFactory.getObject();
            // use the new instance
        }
    }
    
  • Scoped Proxies (@Scope(proxyMode = ...)): For web-specific scopes (request, session, application, websocket), or for a more generic solution with prototype, you can use scoped proxies. Spring injects a proxy that looks like the target bean but in reality delegates to the actual bean instance for the correct, active scope (e.g., a new instance for each request or session).
    @Component
    @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public class RequestScopedBean {
        // ...
    }
    
    @Component
    @Scope("singleton")
    public class SingletonBean {
        @Autowired
        private RequestScopedBean requestScopedBean;
        // ...
    }
    

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.

Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

What are Beans in Spring framework? What does a Spring Bean definition consists of? Different Spring Bean Scope. How do I define the scope of a bean in spring framework? How do I provide beans configuration metadata to the Spring Container? Describe the lifecycle of a Bean in Spring framework. Is a singleton bean thread safe in Spring Framework? Explain the important life-cycle methods of a bean in Spring framework. Explain inner beans in Spring framework? What are the limitations of autowiring in Spring framework? How do I inject java.util.Properties into a Spring Bean? Explain @Required annotation in Spring framework. Explain @autowired annotation in spring framework. How do I make autowired bean property as optional? What is @Resource annotation in Spring framework? How do I configure a bean in my spring application? What kind of exception does spring DAO classes throw? Explain the different ways to configure a Java class as Spring Bean. Difference between id and name attribute of <bean> element in a Spring configuration file. Is Spring Bean with singleton scope thread safe? Difference between @Resource and @Autowired in Spring framework. Explain lazy-init attribute of bean tag in Spring. Can we fetch the inner bean from spring container using its id, if an inner bean defines one? Explain Spring bean inheritance. What is Bean Definition Template in Spring framework? What is spring bean pure inheritance template? Can a spring bean tag with no id or name attribute be created? How do I inject value for a bean property of primitive type? Can spring bean autowire on primitive types? How do I create a stateful bean in Spring framework? Difference between request and prototype bean scope in spring? What is the role of a Spring bean configuration file? Explain Circular Dependency scenario in Spring. Spring Bean marked as abstract by abstract=true needs the corresponding java class be abstract ? Spring Bean: Specify particular implementation of collection in your bean definition. Spring bean: difference between stateless and stateful beans. Can I define spring bean twice with same name in different bean definition file? Can I define spring bean twice with the same bean id in same file? Explain JSR-250 annotation. What is primary annotation in Spring? How to get all the Spring beans implementing a specific interface? What are the attributes of Spring @Transactional annotation? When is a spring bean destroy-method being called? When is a Spring Singleton bean garbage collected? When is a prototype bean garbage collected? Explain BeanPostProcessor beans. Explain no autowiring mode in spring bean. How do you debug Spring configuration? What is component scan in Spring framework? What happens when a singleton bean contains a prototype bean? What happens when a prototype bean has a singleton dependency? Can a singleton bean hold a request- or session-scoped bean? How does Spring handle @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) internally? What are the possible issues with prototype beans in singleton beans? What are "Scope Mismatch" errors? Can we inject a session-scoped bean into a prototype bean? Explain @Lookup annotation usage in this context. When should you use prototype scope vs request scope? What is the default scope in Spring and why? How do you ensure each user session gets a unique bean instance even if it's injected into a singleton service? What happens if you call ApplicationContext.getBean() for a prototype bean multiple times? What are the best practices for using prototype scope? Explain the Scope Injection problem and provide a solution to fix it.
Show more question and Answers...

Spring Interview questions II

Comments & Discussions