Open In App

How to Create a Spring Bean in 3 Different Ways?

Last Updated : 02 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and application programming interfaces (APIs), such as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java Servlet. In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.

Different Methods to Create a Spring Bean

Here we are going to discuss how to create a Spring Bean in 3 different ways as follows: 

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

Method 1: Creating Bean Inside an XML Configuration File (beans.xml)

One of the most popular ways to create a spring bean is to define a bean in an XML configuration file something like this.

<bean id="AnyUniqueId" class="YourClassName">
</bean>

Let us create a simple class Student having two attributes id and studentName and later creating a simple method to print the details of the student.

Example

Java




// Java Program to Illustrate Student Class
 
// Class
public class Student {
 
    // Class data members
    private int id;
    private String studentName;
 
    // Method
    public void displayInfo()
    {
        // Print statement
        System.out.println("Student Name is " + studentName
                           + " and Roll Number is " + id);
    }
}


Now let’s create an XML file named beans.xml file in the project classpath. And inside this beans.xml file, we have to define our Student bean something like this. And that’s it. In this way, you can create beans in spring. 

Example

XML




<?xml version="1.0" encoding="UTF-8"?>
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 
    <bean id="studentAmiya" class="Student">
 
    </bean>
 
</beans>


Method 2: Using @Component Annotation 

Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. @Component is an annotation that allows Spring to automatically detect the custom beans. 

Example: Suppose we have already a Java project and all the Spring JAR files are imported into that project. Now let’s create a simple class named College and inside the class, we have a simple method. Below is the code for the College.java file.

A. File: College.java

Java




// Java Program to Illustrate College Class
 
package ComponentAnnotation;
 
// Class
public class College {
 
    // Method
    public void test()
    {
        // Print statement
        // whenever this method is called
        System.out.println("Test College Method");
    }
}


 
 

Now let’s create a Bean for this class. So we can use @Component annotation for doing the same task. So we can modify our College.java file something like this. And that’s it. 

B. College.java

Java




// Java Program to Illustrate College Class
 
package ComponentAnnotation;
 
// Importing required classes
import org.springframework.stereotype.Component;
 
@Component("collegeBean")
 
// Class
public class College {
 
    // Method
    public void test()
    {
        // Print statement
        System.out.println("Test College Method");
    }
}


Method 3: Using @Bean Annotation

One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods.

Suppose we have already a Java project and all the Spring JAR files are imported into that project. Now let’s create a simple class named College and inside the class, we have a simple method. Below is the code for the College.java file.

A. College.java

Java




package BeanAnnotation;
 
import org.springframework.stereotype.Component;
 
public class College {
 
    public void test(){
        System.out.println("Test College Method");
    }
}


Now let’s create a Configuration class named CollegeConfig. Below is the code for the CollegeConfig.java file

B. CollegeConfig.java

Java




package ComponentAnnotation;
 
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class CollegeConfig {
 
}


Here, we are going to create the spring beans using the @Bean annotation. To create the College class bean using the @Bean annotation inside the configuration class we can write something like this inside our CollegeConfig.java file. Please refer to the comments for a better understanding. 

@Bean
// Here the method name is the
// bean id/bean name
public College collegeBean(){
    // Return the College object
    return new College();
}

Implementation: Below is the complete code for the CollegeConfig.java file that is below as follows: 

Java




// Java Program to Illustrate Configuration in College Class
 
package BeanAnnotation;
 
// Importing required classes
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class CollegeConfig {
 
    // Using Bean annotation to create
    // College class Bean
    @Bean
 
    // Here the method name is the
    // bean id/bean name
    public College collegeBean()
    {
 
        // Return the College object
        return new College();
    }
}


 
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads