In this post, we will discuss two different types of Spring beans, singleton and prototype beans and we will also discuss when to use prototype beans and when to use singleton beans.

If you fancy an assistant on your desk to entertain you, tell you about the weather or your appointments, then I recommend the Anki Cozmo – Collector’s Edition robot (click to check the price on Amazon). The Anki Cozmo will entertain you during those boring or lonely moments at work, or while studying, and will help you to keep your schedule and be more alert throughout the day.

Singleton beans

Most beans that you will use or encounter are singleton beans. Singleton beans are initialized once, either when the application context starts or manually via lazy loading.

Singleton beans as in the name are singleton. This means that once a singleton bean is initialized, the same instance will be reused throughout the application context. This also means that every-time the bean is requested from the application context, the same instance of the bean will be provided.

Singleton beans are ideal as resource intensive components, such as database management services where database connections are opened. Or beans that require resources to be acquired on startup such as system memory or other physical or network resources. For example, you do not want to start a new database connection everytime you need to run a database query. For this, a singleton bean is ideal.

This bean is a regular Spring bean. For testing purposes we added the static instances created counter in order to test the number of times a new instance of the bean class is created. Now, let us go to the bean configuration:

As you can see,  we did not need to state that the bean is a singleton as this is the default. In order to set the bean type, you will need to define the bean scope

Please note that in the previous code snippet, we set the bean scope only for demonstration purposes. Since a bean is singleton by default, it is not required to set the scope of that bean.

Prototype beans

Prototype beans are Spring beans. Prototype beans themselves behave exactly the same as singleton beans. The only difference here is how Spring handles the beans. Let us define a prototype Spring bean.

As you can see, programatically, a prototype bean class looks exactly the same as a singleton. Let us configure the prototype bean in our Java config.

In order to mark a bean as a prototype, we will need to use the @Scope annotation with the value ConfigurableBeanFactory.SCOPE_PROTOTYPE.

If you want to improve your Spring boot skills, then I would suggest that you check out the book “Learning Spring Boot 2.0 – Second Edition: Simplify the development of lightning fast applications based on microservices and reactive programming”(click to check current price on Amazon) by Greg Turnquist. The book covers Spring boot basics and provides an overview of integrating important technologies such as AMQP messaging and REST into your application.

Differences between Prototype beans and Singleton beans

So how does a prototype bean differ from Singleton beans? let us go through some points on how Spring handles the beans differently.

Autowiring

When you autowire a bean, you ask Spring for an instance of the bean from its application context. If you autowire a singleton bean, Spring looks for an existing instance inside the application context and provides you it. If you autowire the bean in multiple places, then Spring will still provide you with the same instance.

When you autowire a prototype bean, Spring will initialize a new instance of the bean. If you autowire the bean in multiple places, then Spring will create a new instance for every place you autowire the bean.

Let us try this by creating a test bean and a spring test where we autowire our test beans. Let us start with our test bean.

Now, let us use this bean inside a Spring boot test. In our spring boot test, we will request our test bean and we will request instances of our singleton and prototype beans.

And the result of this program would be:

As expected, the Prototype bean’s constructor has been called twice. Once for the instance autowired inside our test bean and the second is for the autowired instance inside the test. In contrast, the singleton bean’s constructor is called only once. This is because Spring reuses the same instance.

Requesting a bean instance manually

Requesting a bean instance manually yields the same result as autowiring the bean. Every time you request a singleton bean from the application context, you obtain the same instance. However, if you request a prototype bean, then a new instance is created for you. Let us modify our test bean to add the following method.

Now, let us call our testInstances method in our test as follows:

And the result will look as follows.

Notice that now, the prototype bean is created 3 times. Once inside our test bean via the @Autowired annotation. Once inside the testServiceBean.testInstances() method, and once via the @Autowired annotation inside our test. The singleton bean had only one instance of it created.

Shutting down the beans

There is a fundamental difference between singleton and prototype beans when it comes to managing the shutdown phase of the beans’ lifecycle. The difference is that Spring will clean up singleton beans and destroy them once the containing application context is destroyed. That means that a singleton bean will remain in your JVM memory unless the application context is shutdown or if the bean is manually destroyed.

On the other hand, prototype beans will not be cleaned up by Spring and the bean instances will be left up to the garbage collector for cleaning. Let us explore this with an example. Let us define the destroy method inside both our singleton and our prototype bean.

Now, let us mark the destroy methods in our Java configuration.

And finally, let us run our test again and analyse the logged statements.

Notice that the destroy method of the singleton bean was called, but not the one of the prototype bean. Therefore it is important to manually clean up any resources such as streams and buffers from prototype beans before finishing your use case. This can be done by manually calling the bean’s destroy method at the end of the bean’s usage.

When to use singleton beans and when to use prototype beans

We have compiled below a list of reasons or usages for both beans. Let us start with singleton beans:

  • Useful as “stateless” beans.
  • For beans that require expensive resources on start up such as database connections.
  • For beans that used for caching and sharing data throughout your application.
  • When an orderly and controlled shutdown is required.

The following could be interesting use cases for prototype beans:

  • Stateful beans that fulfill a purpose of a single call or a single use.
  • For entities where Spring support is required. For example, when having a list of “Accounts”, where each account holds different data, but also each account is a spring bean where other spring beans are used.

Summary

In this tutorial, we discussed how to define a prototype bean and a singleton bean. We discussed how spring handles these beans differently at creation time and at shutdown. We also discussed some reasons why one would prefer a scope over the other. Below is a table summarizing the differences discussed in this tutorial.

Singleton beanPrototype bean
Default Spring bean type. Can be explicitly configured by:
@Scope
(ConfigurableBeanFactory.SCOPE_SINGLETON)
Can be configured via the annotation:
@Scope
(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Only one instance is created. It is reused everywhere.A new instance is created everytime the bean is requested.
Destroyed by Spring when the application context shuts down.
The bean’s destroy method is called.
Not destroyed by Spring.
The destroy method is not called.
Cleaned up is done by the garbage collector.
The user is responsible for cleaning up any resources inside the bean.
Preferred scope for beans with heavy startup resources.Preferred scope for beans with lighter startup resources.
Used in stateless situations.Used for stateful situations.

If you would like to learn the fundementals of Spring and become a professional for your career or personal projects, then check out the book Spring in Action: Covers Spring 4

If you like this tutorial, then please make sure to let us know in the comments below.