Bean Instantiation Methods in Spring

Introduction

This is a series and it would make a lot of sense if read in a sequence. You can find all the posts under the heading “Spring Beginners to Professionals“. The previous posts helped us build some understanding around the Spring beans. We also understood that a Spring application is all about wiring beans together and accomplishing tasks. Let us now learn about various bean instantiation methods in Spring.

Bean Instantiation Methods in Spring

There are multiple ways of instantiating beans and  you can instruct Spring to use the one which fits your needs.

Bean Instantiation using Constructors

Using constructors for instantiating bean is a good choice. By default Spring reflectively invokes the no argument constructor of a bean and gets an instance. This means, you must define a Java styled bean if there are no special requirements.

In case there is a mandatory property in the bean which needs to be populated during bean instantiation, then you would choose to have a constructor with an argument. Also, the bean definition will contain a constructor arg element. In such a case, you won’t need a no argument constructor. There are few exception to this, which we can talk when required.

Bean Instantiation using Static Factory Method

Alternatively you can also create bean using static factory methods defined in a class. There is no restriction on the type of object this method can create. Such a method can create objects of the type which contains this method or it can create objects of any other type. There can be more than one static factory method in a class, and they can create and return objects of any type.

Static factory methods are found to be of great use in certain scenarios, one of them being static factories in legacy code. Spring can manage objects created using static factory in legacy codes. There is another very important use case for static factory methods which we will discuss while learning about scopes.

Bean Instantiation using Instance Factory Method

Similar to the static factory methods, we can also use a instance factory method. The method is defined in a bean which is called the factory bean, we can define as many factory methods as required, each creating and returning object of any type.

For this to work, we definitely need to declare a bean definition for the factory bean. And as we declare other beans, we can provide the reference of the factory bean and the specific factory method which is used to create these new beans.

Summary

Here we learnt about various ways on instantiating beans. Next in the row is application configuration and putting the glue between all these code described above. We will learn how to write and boot up a simple Spring application.

This will lay foundation to more complex applications. Further we will discuss the annotation configurations as well. Stay connected.