Spring @Bean – What is Spring Bean with examples

The Spring framework is a popular framework that lets you create enterprise applications conveniently.

The core of the spring framework is dependency injection.

Dependency injection or dependency inversion is a way in which you decouple the conventional dependencies between objects.

To understand dependency injection let’s take an example of the Student and Address class.

As you could see in the above pseudo-code, Student and Address objects are related to each other.

Every student has one Address and every Address must belong to a Student.

Usually, in java, we will create the Address object using new Address() and provide the Address object to Student.

Therefore, whenever you need a student object, you have to create an address object first.

To put it differently, we can say that the Student object is tightly coupled with the Address object.

However, Tight coupling is not good due to various reasons like it will be difficult to test, difficult to manage if there are any changes in the Address class.

To solve this problem dependency injection was introduced.

Spring IoC container ( ApplicationContext and BeanFactory ) is an implementation of dependency injection in Spring framework.

Spring Container configures objects, bundles them, create them and manages their life cycle completely. 

Those objects are called beans in Spring terminology.

In other words, a spring bean is an object that is configured, created, and managed by Spring container.

How to create Spring Bean

There are two ways to create spring beans.

One way is by using XML configuration and another is using annotations.

Earlier we used to define beans in the XML file.

Later the annotation concept came that allows declaring bean using @bean annotation in a configuration file.

If you are not aware then a configuration class is a special class in spring that defines bean’s definition.

Whenever spring container sees a configuration class then it processes them automatically.

Now since we know the basics of spring bean and configuration class lets create bean using @Bean annotation.

Declare a Bean using @Bean

Declaring a bean is easy in the spring framework.

You just have to create a method and annotate that method with @Bean.

Whenever spring container finds the configuration class, it processes that class to find bean definition.

And when spring container sees a method with @Bean annotation, it executes the method and registers the return value as a Bean in the container( ApplicationContext ).

Let’s create a demo to understand the @Bean concept in Spring.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.