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 |
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.
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. |
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.
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
}
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.
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.
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
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:
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");
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);
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);
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.
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.
Some of the most used spring bean annotations include:
@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.
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.
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 {
// ...
}
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
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
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
In addition, Spring provides its own set of web-specific bean scopes in spring:
@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();
}
}
@Bean
@Scope("prototype")
public class BeanClass {
System.out.println("A new BeanClass instance created");
return new BeanClass();
}
@Bean
@Scope("request")
public class BeanClass {
System.out.println("A new BeanClass instance created for current request");
return new BeanClass();
}
@Bean
@Scope("session")
public class BeanClass {
System.out.println("A new BeanClass instance created for current request");
return new BeanClass();
}
@Bean
@Scope("application")
public class BeanClass {
System.out.println("A new BeanClass instance created for current request");
return new BeanClass();
}
@Component
@Scope("websocket")
public class BeanClass {
}
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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
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);
}
}
Here, we'll go through three distinct methods for creating a bean in spring boot.
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.
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.
The spring container takes care of the life cycle of beans.
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.
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.
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.
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.
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Core Java Training | Nov 19 to Dec 04 | View Details |
Core Java Training | Nov 23 to Dec 08 | View Details |
Core Java Training | Nov 26 to Dec 11 | View Details |
Core Java Training | Nov 30 to Dec 15 | View Details |
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.