How to Create Spring Bean in 3 Different Ways?


Spring is a highly popular framework within the Java EE ecosystem. It is an open-source and lightweight framework that empowers Java developers to build reliable, scalable, and simplified business applications. The primary goal of this framework is to offer you a variety of tools for managing your business items.

In contrast to conventional Java frameworks and APIs such as JSP,JDBC and Java Servlet, developing web applications is far simpler.

In Spring, objects—primarily those controlled by the Spring IoC Container. It plays a significant role in the application. A Bean is nothing more than an object that a Spring Ioc Container creates, assembles, and manages in any other way.

Based on configuration metadata that we supply to the container these beans are produced. as XML <bean/> definitions, for instance.

Different Ways to Create a Spring Bean

In this article we will discuss about the ways to create a Spring Bean as outlined below −

  • Creating a Bean within an XML Configuration File

  • Creating a Bean Using the @Component Annotation

  • Creating a Bean Using the @Bean Annotation

Before getting into the explanation for each method let’s create a class called Employee. We will include two attributes Name and Employee number, for those attributes use getters and setters or else we can use lombok to minimize or remove the boilerplate code.

Employee.class

public class Employee {

   private String name;

   private String emp_nbr;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getEmp_nbr() {
      return emp_nbr;
   }

   public void setEmp_nbr(String emp_nbr) {
      this.emp_nbr = emp_nbr;
   }
}

In Java programming, we typically create an instance of a class using the new keyword. However, in Spring, there are alternative approaches to generate instances of bean classes that do not involve the use of new.

It is possible to use a new keyword, but it is not advised because doing so prevents the injection of properties and the use of Autowiring when creating beans.

Method 1: Creating a Bean Within an XML Configuration File 

This is the simplest method of creating a bean, which is defined in the XML configuration file. The beans described in this configuration file are all created and initialised by the Spring container when it starts up, allowing them to be utilised at any moment throughout application context.

Syntax

<bean id="AnyUniqueId" class="YourClassName">
<!-- Property values will be set using setter injection -->
</bean>

How to Create Spring Bean in 3 Different Ways?

We will create a bean for the above Employee class that we have already created.This is how a bean is defined in configuration XML.

<bean id="employee" class="com.hari.sample.Employee">
</bean>

While running the program, the attribute id is employed to uniquely identify the bean and acquire its reference.

By following this approach, we declare a bean, and it can be accessed and utilized in the application using the following method −

public class App{
   @SuppressWarnings({"unchecked", "deprecation"})
   public static void main( String[] args ){
      ApplicationContext context = new AnnotationConfigApplicationContext(Employee.class);
      Employee emp = (Employee)context.getBean("employee");
      System.out.println(emp.getEmp_nbr());
      System.out.println(emp.getName());
   }
}

Method 2: Creating a Bean Using the @Component Annotation

Annotations are utilized to communicate information about a program. It has no direct influence on the functioning of the code they annotate.

The @Component annotation helps Spring to automatically recognise the custom beans.When a Spring component bean is used, it is typically annotated above the class in the following manner −

Example

@Component
public class Employee {

   private String name;
   private String emp_nbr;
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getEmp_nbr() {
      return emp_nbr;
   }

   public void setEmp_nbr(String emp_nbr) {
      this.emp_nbr = emp_nbr;
   }
}

Note − In order to enable component scanning in a Spring Boot application, it is common to specify the base package(s) that should be scanned. This can be done by annotating your main application class with @SpringBootApplication or by using the @ComponentScan annotation explicitly.

Method 3: Creating a Bean Using the @Bean Annotation

One of the fundamental annotations in Spring is @Bean, which is applied to a method to designate it as a provider of a bean managed by the Spring context. Typically, the Spring Bean annotation is commonly used in Configuration classes.

We have previously created an Employee class for this purpose, so we are going to create a Configuration class called EmployeeConfig. The code for this EmployeeConfig.class file is shown below. 

Example

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class EmployeeConfig {
}

Note − The @Configuration annotation in Spring is meant to be used at the class level. If it is applied to methods or fields, a compilation error will occur, indicating that this configuration is not permitted in that particular location.

Now we will utilize the @Bean annotation to construct Spring beans. The @Bean annotation is used inside the configuration class to construct the Employee class bean.

Below is the complete code for the EmployeeConfig.java file −

//Below is a Java program demonstrating the usage of configuration in an Employee class:

// We will include the required classes by importing them
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EmployeeConfig {

   //creating an Employee class Bean
   // using the Bean annotation
   @Bean
   public Employee employeeBean(){

      // Return the Employee object
      return new Employee();
   }
}

Conclusion

In this article we have discussed the ways to create a spring bean with some examples. To implement the above examples one needs to create a spring boot project and need to do necessary configurations to run successfully.

Updated on: 16-Oct-2023

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements