Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Bean?
3.
What is a Spring Bean?
4.
What is Inversion of Control(IOC)?
4.1.
Domain Classes
4.2.
Traditional Approach
4.3.
IoC in Action
5.
Spring Bean Scope
6.
Spring Bean Annotations
6.1.
@Component: 
6.2.
@Configuration:
6.3.
@Controller: 
6.4.
@Repository
6.5.
@Service
7.
When to use @Bean Annotations?
7.1.
Example
8.
Frequently Asked Questions
8.1.
What is a Spring bean?
8.2.
What is the use of Spring bean?
8.3.
What is the use of @bean annotation in Spring?
8.4.
What is the difference between @component and @bean?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Spring Bean

Author Nidhi Kumari
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

To work effectively with Spring and create well-structured and maintainable apps, one must have a solid understanding of Spring Beans. A "Spring bean" is a key concept in the Inversion of Control (IoC) method offered by Spring in the context of Java and Spring Framework. Using the Spring framework, you can increase coding efficiency and decrease the time required to develop a Java application overall.

Spring Bean

Spring beans will hold most of the app's logic code you develop. So, a Spring bean is the basic element of any Spring framework. This article aims to explain spring bean when to use @bean annotations and the scope of Spring Bean. We will also cover Inversion of Control. Before understanding spring bean, let’s discuss what Inversion of Control is.

What is Bean?

A "bean" is an object that contains data and offers getter and setter methods to access and modify that data.  The word "bean" first appeared in the Java programming language, where it is frequently used to refer to a particular kind of class that follows a set of rules and is employed for data processing and visualisation.

What is a Spring Bean?

A bean is an object that a Spring IoC container instantiates, assembles, and generally manages its entire life cycle.

The configuration metadata you provide to the container is used to build these spring beans.  You can configure a spring bean if you initialise a Java POJO class or an XML file in a container via configuration metadata. The basic definition of spring bean contains some information, and this information is known as metadata.

Java POJO Class
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is Inversion of Control(IOC)?

Spring IOC container is one of the essential features of the Spring framework. If you are creating a spring-based app, you must know that every spring object resides in a spring container.

A spring container performs the following operations:

  • Creation of objects.
     
  • Linking all the relevant objects.
     
  • Configuration of various objects.
     
  • Managing the complete lifecycle of objects from creation to deletion.

 

The objects inside the Spring IOC container are known as spring beans.  Let’s know more about its classes and approaches.

Domain Classes

In Spring, "domain classes" refers to the classes that represent the application's objects or business entities. Typical domain classes are plain Java objects (POJOs) with methods to specify the entity's behaviour and attributes to reflect the entity's state. 

These classes, which frequently correlate to the tables in a database in a data-driven application, contain the state and behaviour of the entities.
When using Spring beans, domain classes are frequently the object of data access operations.

Here is the implementation of domain classes:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
   private final Product product;
   @Autowired
   public ProductService(Product product) {
       this.product = product;
   }
   public void displayProductInfo() {
       System.out.println("Product ID: " + product.getId());
       System.out.println("Product Name: " + product.getName());
       System.out.println("Product Price: " + product.getPrice());
   }
}

Traditional Approach

XML-based configuration is used to define Spring beans conventionally. Before the invention of annotations, the main technique for configuring and wiring Spring beans was XML configuration. Even though annotations are more common and practical, traditional systems continue to support and frequently use the XML-based approach.
 

Here is the implementation of the traditional approach:

<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
   <!-- Bean Definitions Go Here -->
</beans>

IoC in Action

The process by which control of creating and managing objects is transferred from the application code to the Spring IoC container is known as inversion of control (IoC), and it is a fundamental idea in the Spring Framework. 

Here is the implementation:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
   public static void main(String[] args) {
       // Load the Spring IoC container with the XML configuration
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       // Retrieve the "Candidate" bean from the container
       Calculator cal = context.getBean("cal", Calculator.class);
       // Use the calculator to perform an operation
       int result = cal.add(10, 20);
       System.out.println("Result: " + result);
   }

Spring Bean Scope

The spring framework provides six scopes for spring beans. These five spring bean scopes are as follows:

  • prototype: The system produces a new instance every time the spring bean is requested.
     
  • request: It is designed for web apps. The work is the same as the prototype scope. For every HTTP request, the system creates a new instance.
     
  • singleton: This is the default scope of a spring bean. For each container, one instance is created.
     
  • session: The container will generate a new bean for each HTTP session.
     
  • global-session: Portlet apps need a global session. Use the global session scope to create global session beans for Portlet apps.
     
  • web-socket: The container will generate a new bean for a specific session.
     

Note: 

1. One can create own scopes since the spring framework is extendable.

2. While using singleton scope, ensure the bean has no shared instance variables.

Spring Bean Annotations

You can find the spring bean annotations using the @componentscan feature and register them as beans in the Spring container. The most common spring bean annotations are as follows:

@Component: 

It can automatically detect the custom spring bean. A bean with the same name as the class name(lowercase first letter) is automatically designated by the class-level annotation @Component.

@Configuration:

 One can mark the bean definition method in the source code using the @configuration annotation.

@Controller: 

Model-View-Controller (MVC) controllers in the Spring framework are represented by the class-level annotation @Controller.

@Repository

The class's ability to store, retrieve, search for, update, and remove objects is indicated by the @Repository.

@Service

It indicates the location of the business logic, which can enhance code reuse.

When to use @Bean Annotations?

When you are using third-party library classes, it’s not practical to use @Component to detect your custom bean. This is because you cannot see the source code when you wish to interconnect components from those libraries.

In such cases, an object that spring should identify as a bean in the application context is returned by the @Bean annotation. Let’s consider an example.

Example

We will start with adding the @Configuration annotation to the config class. We are creating an instance having a name as Example. In your spring app, this will introduce the Example instance as a Bean that you can easily auto-wire with your app. You may also create BeanX and BeanY as Spring Beans and then use references to them when building the Example(instance).

//configuring class
@Configuration
class ExampleConfigurationClass {


//bean with the same name as the class name
    @Bean
    public Example example() {
        return new Example(beanX(), beanY()):
    }


    @Bean
    public ExampleA beanX() {
        return new BeanX();
    }


//Another bean with the same name as the class name
    @Bean
    public BeanY beanY() {
        return new BeanY();
    }
}

 

Frequently Asked Questions

What is a Spring bean?

A bean is an object that a Spring IoC container instantiates, assembles, and generally manages its entire life cycle. The configuration metadata you provide to the container is used to build these spring beans.

What is the use of Spring bean?

Spring beans enable inversion of control by allowing the Spring IoC container to take charge of object creation and management. Instead of directly creating objects with the new keyword, beans are defined in a configuration file or through annotations.

What is the use of @bean annotation in Spring?

In Spring, @bean annotation declares a method as a bean definition. It indicates that the Spring container should call the annotated method to create, customise, and manage the object the method returns.

What is the difference between @component and @bean?

The @Component annotation is used to identify a Java class as a Spring bean.  The @Bean annotation is used in Java configuration classes to define each bean declaration explicitly. It is used with techniques that create bean instances manually.

Conclusion

This article extensively explained the Spring beans. Spring bean is the basic element of any Spring framework. Spring beans will hold most of the app's logic code you develop.

We hope this blog has helped you. We recommend you visit our articles:

If you liked our article, do upvote our article and help other ninjas grow.  You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

Live masterclass