Java

Java Beans in Spring Framework

In this article, we will learn to understand the core concept of Java bean used in Spring framework.

Bean

Java Bean is a core part of a Spring application that is a pure java object represented by a class. It is a runtime entity managed by the IOC container.

The IOC Container creates, initializes, runs, and destroys the bean based on the application requirement.

In the previous article, we created a bean Student that we configured by using the XML and Java annotations.

Spring IOC Container creates the bean object with the help of either XML file or Java annotations that provides the metadata. The IOC uses this metadata for managing the bean objects throughout the application context.

How to Create Java Bean

As we already discussed, Java bean is a class that contains private properties, getters and setters method. You can create the bean of any valid name and entity such as Student. In our case, a Student bean is like the following:

// Student.java

package com.linuxhint.beans;

public class Student {
   
    private int id;
    private String name;


    public String getName() {
        return name;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
   
}

Configuration of Beans in Spring

Spring supports the following three types to configure the bean:

  • XML based configuration
  • Java @Component annotation
  • Java @Bean annotation

Let’s understand one by one.

Configure in XML File

To configure the bean in the xml file, you must use the <bean> tag with the required and supportive attributes such as id and class.

<bean id="emp" class="com.linuxhint.Student"></bean>

The “applicationContext.xml” file looks like the following:

<?xml version = "1.0" encoding = "UTF-8"?>
<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-3.0.xsd"
>

   <bean id = "emp" class = "com.linuxhint.beans.Student">
      <property name = "name" value = "Rohan"/>
   </bean>
</beans>

The <property> tag is optional and required if you want to set static values for the bean.

While creating the bean and setting the metadata configuration, we supply the following optional attributes to the bean such as the following:

  • The bean name should be a fully qualified name such as com.linuxhint.Student.
  • We must specify the bean scope, callback, etc. to manage the bean flow.
  • The bean dependencies that are dependent on the other beans and require while creating the bean object.

Configure Using the @Component Annotation

If you want to use the Java-based annotation and don’t like to use the XML code, this is a suitable way to configure the bean for you.

Here, we use the @Component annotation with the Student class to mark the class as a bean. The Spring IOC treats this class as a bean and manages it during runtime.

This annotation is a stereotype and located into the org.springframework.stereotype package. The bean looks like the following after adding the @Component annotation:

// Student.java

import org.springframework.stereotype.Component;
@Component
public class Student {
   
    private int id;
    private String name;
   
    // getters
    // setters
}

While using this annotation, we must use the <context:component-scan> tag in the applicationContext.xml file so that the IOC can scan all the component of your project.

// applicationContext.xml

<?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">
<context:component-scan base-package="com.linuxhint.*"></context:component-scan>
   
</beans>

Configuration Using @Bean Annotation

This is another way to configure the bean by using the @Bean annotation. In this case, we must create a config class with the @Configuration annotation and return the object of the bean by using the @Bean annotation. Let’s understand with the source code.

This is our Student bean class:

// Student.java

public class Student {
   
    private int id;
    private String name;
   
    // getters
    // setters
}

This is our config class that returns a bean object:

// SpringConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.linuxhint.beans.Student;
@Configuration
public class SpringConfig {
   
    @Bean
public Student StudentBean()
      {
        return new Student();
      }
}

All these are the valid ways to configure and create the bean in spring application. You can follow any of these but the most modern approach is the annotations-based configuration is either using the @Component or @Bean annotation.

Bean Definition Properties

The XML <bean> tag supports several attributes, some of them are listed here. You can refer this table to check the supported properties of bean and can use for configuring a bean object.

Property Name Brief
Class It specifies the class name for the bean object.
Name It specifies the unique name for the bean object.
Scope We can use this attribute to specify the scope such as prototype or singleton.
Constructor arguments We can use it to specify the constructor-based dependency injection in the application.
Property Name Brief
Properties It is used to set the property-based dependency injection.
Autowiring mode For the bean auto wiring.
collaborators and lazy initialization mode For setting the lazy bean initialization in the application.
Initialization method For setting the method that executes at the time of the bean initialization in the application.
Destruction method A method that executes before destroying the bean object.

Let’s understand some attributes of the tag while configuring the bean.

The ID and class attribute that we already seen in the article. So, let’s explore with the lazy-init and the others.

Lazy Bean Initialization

To declare a bean lazy, we can use the lazy-init attribute that tells the IOC not to create the bean at the time of initialization.

<bean id = "..." class = "..." lazy-init = "true">
      <!-- Configuration for dependency injection go here -->
</bean>

Setting the Init Method for Bean

To execute a method at the initialization of a bean, spring provides the init-method attribute that specifies the method.

<bean id = "..." class = "..." init-method = "...">
      <!-- Configuration for this bean go here -->
</bean>

Setting the Destruction Method for Bean

Similarly, we can specify the method that executes at the bean destroy time. For this purpose, we use the destroy-method attribute.

<bean id = "..." class = "..." destroy-method = "...">
      <!-- Configuration for this bean go here -->
</bean>

Conclusion

In this article, we learned the Java Bean concept in depth with several configuration techniques. In the next article, we will learn its life cycle and its useful methods.

About the author

Irfan Khan

I’m a software programmer having more than 5 years of development experience in Java and related technology. I love to write technical content as well and love to share the technical knowledge to make it available for all.