Scoped Bean Prototype Bean problem: Springboot

Vignesh A Sathiyanantham
2 min readDec 27, 2021

--

In Springboot when a bean is created, by default it is Singleton but if you annotate the bean with the scope as “prototype” still the bean are singleton in some cases, I this article we will see how we can avoid that problem and get a new instance of the Bean every time you get the bean object.

Even if your bean is annotated as a scope prototype and if the bean is created from the singleton bean then the bean will be a singleton this problem is known as Scoped bean injection problem

Singleton bean returns the same bean object no matter whatever it is being referred to, in fact, all the default bean scope is a singleton in the Spring

Prototype Bean

There are 6 scopes you can set to the bean in the latest spring boot version,

  • singleton
  • prototype
  • request
  • session
  • application
  • websocket

The last 4 beans are only suitable for the web-aware application

A bean with the prototype scope will return a different instance every time it is requested from the container. It is defined by setting the value prototype to the @Scope annotation in the bean definition:

@Service
@Scope(value = "prototype")
public class Class1 implements Executor {
@Override
public String execute() {
return Integer.toHexString(System.identityHashCode(this));
}
}

Problem Statement

As per the Spring bean life cycle, all the beans injected are singleton by default. No matter whatever the scope is defined to spring beans they will be singleton by default. They will not recreate a new instance in case of a prototype bean as it used Autowired or constructor injection will be part of the application startup lifecycle.

Solution

Loading the bean through the application context dynamically will solve the problem.

@Service
public class FactoryUtil implements ApplicationContextAware {

private static ApplicationContext context;

public FactoryUtil() {
}

public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
}

The full source code of the project is available in my Github repo

Originally published at Vignesh A S — Blog.

--

--

Vignesh A Sathiyanantham
Vignesh A Sathiyanantham

Written by Vignesh A Sathiyanantham

Decade of experience in building product related to private datacenter and public cloud #Java #AWS #VMware #Python