What is Bean in Java Spring

This article explores “What is Bean in Java Spring”- Inversion of Control and the most commonly used spring bean, how to use it, bean scopes in spring, and the bean lifecycle. We will also explain the semantics represented by each of the Spring stereotype annotations. The table of contents below allows you to quickly navigate to different sections of the Java bean string tutorial in detail.

Java Bean is a modular programming framework. Beans are the objects that make up the framework of your Spring application and are controlled by the Spring IoC container so that they can be accessed in different contexts. Not only that, but it's also very low maintenance.

Learn how Java spring bean annotations lead to a clean, layered design and how the different parts of an application can be kept separate. Also, they make configuration smaller because we no longer have to define beans manually. The configuration metadata you give the container is used to make these beans. So get into brief!

What is Bean in Java Spring: Table of Content

What is bean in java spring?

The Spring Bean is the fundamental component of any Spring application. To put it simply, a bean is an object that is created, constructed, and managed by the Spring IoC container. We must understand it before we begin working with the Spring Framework.

The Spring Framework relies heavily on the idea of a Spring Bean. Understanding this concept is critical for grasping the framework and using it effectively. The Spring IoC manages the life cycle of the Spring Bean. 

JavaBeans are classes that contain many objects into one object (the bean). The word "Bean" encompasses the following standards, which strive to produce reusable Java software components.

  1. All Java Bean properties must be private and have a public getter and setter methods. 
  2. It must have a public zero-argument function Object().
  3. Must implement Serializable.
If you would like to enrich your career and become a professional in Java Spring, then enroll in the “Java Spring Training”  Course. This course will help you to achieve excellence in this domain.

Inversion of Control (IOC)

To put it briefly, Inversion of Control (IoC) is a technique whereby an object declares its dependencies without really creating them. When passed to an IoC container, this object instructs it to construct such dependencies.

Before we get into the IoC, let's start by declaring a few domain classes.

  • Domain Classes
  • Traditional Approach
  • Bean Configuration
  • IOC in action

1. Domain Classes

Let's say there's a class declaration:

public class Company {
    private Address address;
    public Company(Address address) {
        this.address = address;
    }
    // getter, setter and other properties
}
Copy

This class requires a partner of type Address:

public class Address {
    private String street;
    private int number;
    public Address(String street, int number) {
        this.street = street;
        this.number = number;
    }
   // getters and setters
}

2. Traditional Approach

Typically, we use the constructors for a class to create objects:

Address address = new Address("High Street", 1000);
Company company = new Company(address);

Consider a programme with dozens or perhaps hundreds of classes. Sometimes we wish to share a single instance of a class throughout the entire application, other times we require a unique object for each use case, etc.

The management of so many objects is nothing short of a nightmare. Here is when control inversion comes to the rescue.

Instead of manually creating its dependencies, an object can retrieve them through an IoC container. All that is required is to give the container with configuration details.

3. Bean Configuration

First of all, let's add the @Component annotation to the Company class:

@Component
public class Company {
    // this body is the same as before
}
Here's a configuration class supplying bean metadata to an IoC container:
@Configuration
@ComponentScan(basePackageClasses = Company.class)
public class Config {
    @Bean
    public Address getAddress() {
        return new Address("High Street", 1000);
    }
}

A bean of type Address is made by the configuration class. It also has an annotation called @ComponentScan, which tells the container to look for beans in the same package as the Company class.

When a Spring IoC container makes objects of these types, they are all called Spring beans because the IoC container manages them.

4. IoC in Action

To construct a container from the beans we defined in the configuration class, we require an instance of the AnnotationConfigApplicationContext class:

ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

A quick test proves that our beans exist and what they are worth:

Company company = context.getBean("company", Company.class);
assertEquals("High Street", company.getAddress().getStreet());
assertEquals(1000, company.getAddress().getNumber());

The result shows that the beans were made and set up correctly by the IoC container

MindMajix Youtube Channel

Get Beans

Basically, the method responsible for retrieving a bean instance from the Spring container is the BeanFactory.getBean() method. 

Usually, in the place of BeanFactory, we use one of the known implementing classes as by documentation here. Whatever implementation you use, there are (by BeanFactory) different signatures by which we can retrieve a bean from the Spring container:

  • By name
  • By name and type
  • By type
  • By name with constructor parameters
  • By type with constructor parameters 

By name: 

If you give it a name, it will return an object if there is a bean in the application context with that name. If not, it will throw a NoSuchBeanDefinitionException.

#by name
Object animal = context.getBean("animal");

By name and type: 

In the presence of a name and a type, this method returns a bean of that type if it exists in the application environment; this method can be helpful because it eliminates the need to cast the object returned.

In the case that no such bean definition exists, this method will throw NoSuchBeanDefinitionException; otherwise, it will throw BeanNotOfRequiredTypeException.

#by name and type
Animal animal = context.getBean("animal", Animal.class);

By type: 

it's very much like the previous one, except that there may be multiple instantiated beans of the same type, leading to a NoUniqueBeanDefinitionException.

#by type
Animal animal = context.getBean(Animal.class);

By name with constructor parameters: 

It is possible to use the following syntax to specify the bean name and function Object() parameters:

#by name and constructor parameters
Animal fuffyAnimal = (Animal) context.getBean("animal", "Fuffy", 5);

In this case, we get a 5-year-old animal named Fuffy. But if the bean is singleton (not a prototype), we can get BeanDefinitionStoreException.

By type with constructor parameters: 

It is similar to the last, but we have to pass the type instead of the name, and the bean can't be a singleton:

#by type and constructor parameters
Animal fuffyAnimal = (Animal) context.getBean(Animal.class, "Fuffy", 5);

To retrieve beans from the container, we typically use the ApplicationContext to invoke these primary methods provided by the BeanFactory interface.

Moreover, we rely on auto wiring and dependency injection to get the beans inside another Spring bean so that we don't have to combine logic with a framework-related technique for getting beans.

Most used Spring Bean annotations

Some of the most used spring bean annotations include:

  1. @Component
  2. @Repository 
  3. @Service
  4. @Controller
  5. @Configuration

Spring Bean

1. @Component

@Component is an annotation that goes on a class. Spring Framework automatically finds classes marked with @Component during the component scan:

@Component
class CarUtility {
    // ...
}

As a default, all bean instances of this class will share the same name as the class name, but with a lowercase beginning. The value argument of this annotation is optional and can be used to define a different name.

Beans annotated with @Configuration, @Service, @Repository, or @Controller all follow the same conventions for naming due to the fact that they are all meta-annotations of @Component. Spring also detects them mechanically during the scanning procedure for individual components.

2. @Repository

Classes annotated with @Repository are typically DAOs or repositories and constitute the application's database access layer.

@Repository
class VehicleRepository {
    // ...
}

The use of this annotation allows for the automatic translation of persistence exceptions, which is a definite plus. By default, Spring will convert any native exceptions thrown inside a class annotated with @Repository using a persistence framework like Hibernate into derived classes of Spring's DataAccessException.

3. @Service

The @Service annotation will be used to designate a class as part of the service layer, which typically houses the application's business logic:

@Service
public class VehicleService {
    // ...    
}

4. @Controller

In Spring MVC, a class's use as a controller is indicated to the Spring Framework using the @Controller class annotation.

@Controller
public class VehicleController {
    // ...
}

Related Article>>>Spring Boot vs Spring MVC

5. @Configuration

Methods annotated with @Bean can be found in configuration classes that define beans.

@Configuration
class VehicleFactoryConfig {
    @Bean
    Engine engine() {
        return new Engine();
    }
}

Related Article>>>Spring Cloud Tutorial

Bean Scopes In Spring

The bean's scope determines how long it will live and who can see it in various scenarios. Singleton and prototype are examples of basic scopes, while request, session, application, and WebSocket are examples of web-aware scopes that can be used with beans.

You can declare a bean's scope when you define it. For the spring bean example, to make a new bean instance every time one is needed, you should set the bean's scope attribute to prototype. 

There are a total of five scopes available within the Spring Framework. However, three of them require a web-aware ApplicationContext in order to be used.

In the spring, there are many ways to use your beans. The most important parts of the framework are

  • singleton – a single instance
  • prototype – multiple instances

In addition, Spring provides its own set of web-specific bean scopes in spring:

  • request
  • session
  • global session
  • Application

Spring Bean Scopes

SINGLETON

  •  The bean definition is now limited to a single instance per Spring IoC container (default).
  • For each container, only one instance of the bean will be created. This is the spring beans' default scope. When using this scope, make sure the bean does not have any shared instance variables, as this could cause data inconsistency issues.

Singleton Java configuration:

@Configuration
public class AppConfiguration {
@Bean
@Scope("singleton")  //This statement is redundant - singleton is default scope
public class BeanClass {
System.out.println("A new BeanClass instance created");
return new BeanClass();
}
}

PROTOTYPE

  • A single bean definition can therefore be used to create an unlimited number of objects.
  • Each time you request the bean, a new instance will be produced.

Prototype Java configuration:

@Bean
@Scope("prototype")  
public class BeanClass {
System.out.println("A new BeanClass instance created");
return new BeanClass();
}

REQUEST

  • This restricts the application of a bean definition to a certain HTTP request. This only applies when the Spring ApplicationContext is one that is aware of the web.
  • Similar to prototype scope, but created with web apps in mind. Every HTTP request will produce a fresh instance of the bean.

Request Java configuration:

@Bean
@Scope("request")  
public class BeanClass {
System.out.println("A new BeanClass instance created for current request");
return new BeanClass();
}

SESSION

  • This limits the definition of a bean to an HTTP session. Only works in a Spring ApplicationContext that knows about the web.
  • Each HTTP session will cause the container to make a new bean.

Session Java configuration:

@Bean
@Scope("session")  
public class BeanClass {
System.out.println("A new BeanClass instance created for current request");
return new BeanClass();
}

APPLICATION

  • During a ServletContext's lifetime, there will only ever be a single instance produced and active at any given time. This only applies when the Spring ApplicationContext is one that is aware of the web.

Application Java configuration:

@Bean
@Scope("application")  
public class BeanClass {
System.out.println("A new BeanClass instance created for current request");
return new BeanClass();
}

WebSocket

  • WebSocket will only create and make available one instance for the whole time it is used. Only true for a Spring application that knows about the web. Context

WebSocket Java configuration:

@Component
@Scope("websocket")
public class BeanClass {
}

Populating Bean properties 

Each and every metadata configuration holds the attributes necessary to define a Spring bean.

Almost all of Spring's properties have default settings that can be used to quickly and easily create working bean declarations. It is useful to understand how to alter the default settings.

  • Bean class

When you define a bean, you link it to a specific class in your programme. The primary characteristic of a bean is this class itself.

When Spring searches for a bean's dependents, the class property is used as the default identifier. Does that rule out the possibility of having different bean definitions for the same class? No. It's not impossible. However, in such a scenario, you need to use a different bean identifier: a name, to avoid confusion.

This property must always be present. This file outlines the Spring Framework bean class that must be present in order to construct the bean.

  • Bean name

Spring bean name is a string that is unique to each bean that Spring uses to identify it. In contrast to the bean class, names must be unique throughout the entire application. You can't talk about two different kinds of beans with the same name.

You don't have to set a name for every bean you make, which is good news. Spring makes up names on the fly that it uses internally. You can use the default setup if you don't want to use bean names to find them.

The main time you need to use bean names is when you use the @Bean annotation to define multiple beans for the same class. In this case, names let you find a specific instance of a bean that you want to use as a dependency for another bean.

  • Bean dependencies

Beans are objects that can be utilized to do a variety of tasks by utilizing other beans. Whenever Spring builds an object with defined dependencies, the framework must first generate those dependencies. There may be further requirements within these dependencies.

Object-oriented programming typically involves dealing with a massive network of interconnected items. We do not need to deliberate on the details of building this graph. Object creation doesn't require us to consider a certain timeline. For us, spring accomplishes all of this.

Related Article>>>Spring Boot Interview Questions

Spring Bean Life Cycle annotations?

The spring container is in charge of the entire bean life cycle. The spring container is the first thing that gets started whenever we run the programme. The container then constructs the requested bean instance and injects any necessary dependencies. When the spring container is closed, the bean is permanently closed.

To implement the bean life cycle in Spring, the Spring framework gives you two annotations:

@PostConstruct

@PreDestroy

In most cases, the names of annotations explain what they are for. This method is called "postConstructs" because it is performed after the class's properties have been constructed. The term "PreDestroy" refers to the action taken just before the bean is destroyed.

Life Cycle methods

Step#1: Create a Project in Eclipse/STS 

1) Start up your Eclipse IDE and go to new > project > Maven Project > next.

2) Click "Create a simple project (skip archetype selection)"

3) Tell me what the Group Id and Artifact Id are. Group Id uniquely identifies your project among all. So it could be something like com.dev.spring.lifecycle. Artifact Id could be something like a project name, so we could put SpringLifeCycleExample as the artifact id here.

4) Hit the "Finish" button. You'll get a new project based on Maven.

Step#2: Modify pom.xml

A pom.xml file is generated whenever a new project is started. Providing the dependencies for the most fundamental Spring jars is what this file is about. 

The @PostConstruct and @PreDestroy annotations are not part of the Spring, which is a key distinction to make. They are included in the common-annotations.jar file that is part of the Java EE (JEE) package. In order to use these annotations after Java EE was deprecated in Java 9 and deleted in Java 11, an additional dependency, javax.annotation-api, is required. There is no need to add this dependency if you are not using Java 8 or higher.

Put the following code inside the dependencies> element in your pom.xml file. The most recent stable release of your choosing can be provided if you so want.

<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-core</artifactId>
     <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

When the pom.xml file is saved, the necessary jars are downloaded immediately.

Step#3: Create a Pojo Class

Now, we must now develop a POJO class with two life cycle methods that use annotations: @PostConstruct and @PreDestroy.

package com.dev.spring.bean.lifecycle;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class Person {
   private String name;
   private Integer age;
   public Person() {
      super();
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
     this.name = name;
   }
   public Integer getAge() {
      return age;
   }
   public void setAge(Integer age) {
      System.out.println("Setting Person's Age");
      this.age = age;
   }
   @Override
   public String toString() {
      return "Person [name=" + name + ", age=" + age + "]";
   }
   @PostConstruct
   public void initMethod() {
      System.out.println("Inside init method");
   }
   @PreDestroy
   public void destroyMethod() {
      System.out.println("Inside destroy method");
   }
}

Don't forget to annotate the two life cycle approaches you to deploy.

Step#4: Create a configuration file (config.xml)

In addition to defining the bean, the <context:annotation-config/> tag must be specified. Annotations within the programme will become functional. This tag is required for using annotations in your application.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- bean definitions here -->
<context:annotation-config/>

<bean name="person" class="com.dev.spring.bean.lifecycle.Person">
    <property name="age" value="24"/>
    <property name="name" value="Person-1"/>
</bean>

</beans>

Spring's documentation on XSD Configuration can be consulted for the necessary schema definitions before constructing an XML configuration file. To facilitate our planned use of the Spring framework's beans and context module, we have extended the schema to include only those components.

Step#5: Create a Test class

Let's define a main() method in a test class and see if our code works.

package com.dev.spring.bean.lifecycle;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
   // ApplicationContext ctx= new ClassPathXmlApplicationContext("com/dev/spring/bean/lifecycle/config.xml");
   AbstractApplicationContext ctx= new ClassPathXmlApplicationContext("com/dev/spring/bean/lifecycle/config.xml");
   Person person = (Person) ctx.getBean("person");
   System.out.println(person);
   //registering shutdown hook
   ctx.registerShutdownHook();
   }
}

In order to use the destruct function of the spring bean life cycle, we need to call registerShutdownHook() method. AbstractApplicationContext provides access to this function. 

Hence, we are utilizing AbstractApplicationContext interface in place of ApplicationContext interface to access spring context.

Step#6: Test Output

When the programme is executed, the results will appear as shown below:

Setting Person's Age
Inside init method
Person [name=Person-1, age=24]
Inside destroy method

From the output, it's clear that the init() method is called after all the properties have been set. At the last call to the destroy() method.

Related Article>>>Java Spring Interview Questions

Bean in Java Spring FAQs

1. What is a bean in spring boot with example?

In a Spring boot application, a bean is just a Java object that is made when the application starts by the Spring framework. The object could be a configuration, a service, a database connection factory, or just about anything else.

Example: 

We can use both annotation-based and XML-based configurations for stand-alone apps. The only rule is that the context has to be set up somewhere in the programme before it can be used.

package com.journaldev.spring.main;
import java.util.Date;
public class MyService {
public void log(String msg){
System.out.println(new Date()+"::"+msg);
}
}

2. How to create beans in spring boot?

Here, we'll go through three distinct methods for creating a bean in spring boot.

  1. Using @Bean Annotation
  2. Using @Component Annotation
  3. Creating Bean Inside an XML Configuration File (beans.xml)

3. What is the scope of beans in spring?

The scope of spring beans enables more granular control over the production of bean instances. Sometimes we want to construct a bean instance as a singleton, while in other instances, we may want it to be created once per request or session.

4. What is IOC in spring?

IoC Spring (Inversion of Control) is the heart of the Spring Framework as the container. Everything about the objects' creation, configuration, and assembly, as well as their full life cycle, is handled by this. The Container employs Dependency Injection(DI) to manage the components that make up the application.

5.  How do beans work in Spring?

The spring container takes care of the life cycle of beans. 

  • First, the spring container starts up when we run the programme. 
  • After that, the container creates an instance of a bean based on the request.
  • And then dependencies are injected. 
  • And finally, when the spring container is shut, the bean is destroyed.

6. Why are Java Beans Serializable?

Java Bean is serializable at all times. Serializable does not declare any methods; instead, it serves as a marker to inform the Object Serialization tools that your bean class is serializable. Marking a class as Serializable indicates to the Java Virtual machine (JVM) that the class is compatible with the default serialization method.

7. What is JavaBean used for?

JavaBeans is a model that can be moved around and works on any platform. It is written in the Java Programming Language. The parts of it are called "beans." JavaBeans are classes that put together a group of objects into a single object. It makes it easier to get to these objects from more than one place.

8.  Are JavaBeans still used?

Enterprise JavaBeans or EJB is one piece of technology that may seem old-fashioned now that APIs are becoming more popular, but it is still used by more than 23,500 companies around the world.

9. What is the difference between JavaBean and Spring bean?

  • Spring IOC does not manage Java Bean, but Spring Bean is. 
  • Spring Bean doesn't have to be able to serialize, but Java Bean always is. 
  • Java Bean must have a no-args function Object() { [native code] } by default, but Spring Bean does not. 
  • A Java object can be at the same time a JavaBean, a POJO, and a Spring bean.

10. What are the features of JavaBeans?

  • The default function Object() provided by JavaBeans lacks any precondition or arguments.
  • JavaBeans are capable of serialization and can implement the Serializable interface.
  • JavaBeans typically contain multiple getter and setter methods.
  • Multiple properties can be read or written for JavaBeans.

Conclusion

To wrap up, this article has covered the Java spring bean definition and configuration metadata. In addition, we saw how the Spring IoC container handles them. A working example was also defined in order to obtain a comprehensive analysis of the topic. Now, you are also familiar with how Spring builds objects based on the bean definitions you provide. Feel free to ask any questions in the comment section.To enrich your career in Java spring, enroll your names on Java Spring Training Course to gain in-depth knowledge of the spring configurations.

Course Schedule
NameDates
Core Java TrainingJul 13 to Jul 28View Details
Core Java TrainingJul 16 to Jul 31View Details
Core Java TrainingJul 20 to Aug 04View Details
Core Java TrainingJul 23 to Aug 07View Details
Last updated: 07 Apr 2023
About Author

I am a passionate content writer at MindMajix.  I write articles on multiple platforms such as Power BI, Blockchain, Fintech, Machine Learning, Artificial Intelligence and other courses. My work covers a variety of niches including the IT industry, E-commerce, education, fashion, product descriptions, well-researched articles, blog posts, and many more. Basically, I put love into words and help you connect with the people + moments that matter. You can find me on my Linkedin.

read less