Bean Definition

Bean Definition

In this tutorial, we will discuss bean definition in the spring framework. Bean is a Software Reusable Component. It is a regular java class containing properties and the corresponding setXXX(-) and getXXX() methods created and managed by IOC Container in Spring Framework.

Rules and Regulations to write Bean classes
  • Bean classes must be POJO classes, and they must not extend or implement any predefined Library except java.io.Serializable marker interface.
  • Bean must be declared as “public”, “Non-abstract,” and “non-final.”

The main intention of declaring bean class as “public” is to make bean class scope available to IOC Container to create objects. The main purpose of declaring the bean class as “Non-abstract” is to create an object. The main intention to declare bean classes as “Non-final” is to extend one bean class to another bean class to improve reusability.

  • In Bean classes, we have to declare all properties as “private” and all behaviors as “public,” which will improve “Encapsulation.”
  • If we want to provide any constructor in the bean class, then provide a constructor. It must be a 0-arg constructor and “public” constructor because IOC Container will search and execute public and 0-arg constructor while instantiating bean.

Suppose we want to use Beans in Spring applications. In that case, we must configure that bean classes in the spring beans configuration file because IOC Container will recognize and create Bean objects by getting bean class details from the beans configuration file only. There are three ways to provide beans configurations in spring applications.

  1. XML Configuration
  2. Java Based Configuration
  3. Annotations Configuration
1. XML Configuration

To provide beans configurations in the beans configuration file, we have to use the following XML tags.

<beans>
   <bean id="--" name="--" class="--" scope="--">
      <property name="--" value="--"/>
   </bean>
</beans>

Where,

  • The “<beans>” tag is the root tag in the beans configuration file.
  • The “<bean>” tag can provide configuration details of a particular bean class.
  • The “class” attribute in can provide a fully qualified bean class name.
  • The “<property> tag can represent a particular property [variable] in bean class, and it will set the specified value to the respective bean property by executing setXXX(-) method.

Difference between “id” attribute and “name” attribute in <bean> tag?

  • ‘id’ attribute can take exactly one identity to the bean object, and it will not allow more than one identity.
  • ‘name’ attribute in <bean> tag can allow more than one identity name to the bean object, wherein multiple values only first value is treated as the actual bean identity. The remaining names are alias names for the bean object. In this context, while providing alias names to the bean object, we have to use either ‘,’ or ‘;’ or [space] as delimiter[separator].

E.g 1

<beans>
   <bean id="emp1" class="com.ashok.spring.beans.Employee"/>
</beans>

Employee emp = (Employee)context.getBean("emp1");

Output: Valid.

E.g 2

<beans>
   <bean id="emp1 emp2 emp3" class="com.ashok.spring.beans.Employee"/>
</beans>

Employee emp = (Employee)context.getBean("emp1");

Output: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ' emp1 ' is defined.

Note

Similarly, the following cases are also be invalid.

<bean id="emp1,emp2,emp3" class=" com.ashok.spring.beans.Employee "/>->Invalid

<bean id="emp1; emp2; emp3" class=" com.ashok.spring.beans.Employee "/>->Invalid

<bean id="emp1emp2emp3" class=" com.ashok.spring.beans.Employee "/>-> Valid

E.g 3

<beans>
   <bean name = "emp1" class = "com.ashok.spring.beans.Employee"/>
</beans>

Employee emp = (Employee) context.getBean(“emp1”);

Output: Valid.

E.g 4

<beans>
   <bean name="emp1 emp2 emp3" class="com.ashok.spring.beans.Employee"/>
</beans>

Employee emp = (Employee)context.getBean(“emp1”);

Output: Valid

Note

Similarly, the following cases are also be valid.

<bean name="emp1,emp2,emp3" class=" com.ashok.spring.beans.Employee "/>
<bean name="emp1; emp2; emp3" class=" com.ashok.spring.beans.Employee "/>

Note

It is possible to use both ‘id’ attribute and ‘name’ attribute in single <bean> tag.

E.g 5

<beans>
   <bean id=”emp1” name="emp2" class="com.ashok.spring.beans.Employee"/>
</beans>

Employee emp1 = (Employee)context.getBean(“emp1”);
Employee emp2 = (Employee)context.getBean(“emp2”);

Note

It is possible to provide bean alias names explicitly from outside of the bean definition in configuration file by using <alias> tag.

<alias name="--" alias="--"/>

Where “name” attribute will take bean logical name which we specified with “id” attribute in beans configuration file. Where “alias” attribute will take alias name.

<beans>
   <bean name="emp1" class=" com.ashok.spring.beans.Employee "/>
      <alias name="emp1" alias="emp2"/>
      <alias name="emp2" alias="emp3"/>
   </bean>
</beans>

Employee emp1 = (Employee)context.getBean(“emp1”); // Valid
Employee emp2 = (Employee)context.getBean(“emp2”); // Valid
Employee emp3 = (Employee)context.getBean(“emp3”); // Valid

In J2SE applications, we can define scopes to the data by using the access modifiers like public, protected, , and private. Similarly, in the Spring framework, to define scopes to the beans spring framework has provided the following scopes.

  1. Singleton Scope [Default Scope]
  2. Prototype Scope
  3. Request Scope
  4. Session Scope
  5. GlobalSession Scope
  6. Application Scope
  7. WebSocket scope
1. Singleton Scope
  • It is the default scope in Spring applications.
  • If we use this scope to the bean, IOC Container will create a Single Bean object for the single bean definition in the Spring config file.
  • This approach will return the same bean object every time requesting the bean object.
  • When we request a bean object the first time, IOCContainer will create a bean object and store it in Cache memory. Then, every time accessing the bean object, IOCContainer will return the same bean object reference value without creating new Bean objects.

E.g

<bean id = "emp" class = "com.ashok.spring.core.bean.scopes.singleton.beans.Employee" scope="singleton">

System.out.println(context.getBean("emp"));// Employee @a111

System.out.println(context.getBean("emp"));// Employee @a111
2. Prototype Scope
  • It is not the default Scope in the Spring framework.
  • In Spring applications, if we provide a “prototype” scope in the bean configuration file, then IOC Container will create a new Bean object when calling the getBean(–) method.

E.g.

<bean id = "emp" class = "com.ashok.spring.core.bean.scopes. prototype.beans.Employee" scope="prototype">
System.out.println(context.getBean("emp"));// Employee @a111
System.out.println(context.getBean("emp"));// Employee @a222
System.out.println(context.getBean("emp"));// Employee @a333 
3. Request Scope
  • This scope is not helpful in Standalone Applications [Spring Core Module]. It will be used in Web applications that are prepared based on the Spring Web module.
  • Request Scope can create a separate bean object for every request object.
4. Session Scope
  • Session Scope is used in web applications that are prepared based on the Spring web module, and it is not applicable in Standalone Applications.
  • Session Scope allows creating a separate bean object for every Session object in web applications.
5. GlobalSession Scope
  • This scope is not helpful in standard applications, and it is useful in portlet applications which are prepared based on the Spring web module.
  • Global Session scope allows creating a separate bean object for every portlet Session.
6. Application Scope
  • This scope is not helpful in standalone Applications, and it is useful in web applications prepared based on the Spring web module.
  • ApplicationScope allows the creation of a separate bean object for every ServletContext object.
7. Websocket Scope
  • This scope is useful in web applications that are prepared based on the spring web module.
  • WebSocket scope allows the creation of a separate bean object for a single WebSocket lifecycle.
  • Suppose we use the scopes like request, session, globalSession, application, WebSocket, etc., in standalone applications which are prepared based on the spring core module. In that case, Container will raise an exception like “java.lang.IllegalStateException”.

Note

Spring Framework has provided an environment to customize the existed scopes, but it is not suggestible. The spring framework has provided an environment to create new scopes in spring applications.

2. Java Based Configuration

In Spring, up to Spring2.4 version, the Spring beans configuration file is mandatory to configure bean classes and their metadata. Right from the Spring3.x version, the Spring beans configuration file is optional because the Spring3.x version has provided Java Based Configuration as a replacement for XML documents.

If we want to use Java Based Configuration as an alternative to the Spring beans configuration file in Spring applications, we must use the following steps.

1. Create Bean classes as per the requirement.
2. Create Beans configuration class with the following annotations.

org.springframework.context.annotation.@Configuration: It able to represent a class as configuration class.
org.springframework.context.annotation.@Bean: It will be used at method to represent the return object is bean object.

3. In Test class, Create ApplicationContext object with the

org.springframework.context.annotation.AnnotationConfigApplicationContext implementation class.

ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);

4. Get Bean object from ApplicationContext by using the following method.

public Object getaBean(Class c)

E.g.

Employee emp = context.getBean(Employee.class);

5. Access business methods from Bean.

E.g

Bean class

package com.ashok.spring.core.bean.javabasedconfig.beans;

/**
 * 
 * @author Ashok Kumar
 *
 */
public class Employee {
   private String empName;
   private String empId;
   private String empAddress;
   private double salary;

   public String getEmpName() {
      return empName;
   }

   public void setEmpName(String empName) {
      this.empName = empName;
   }

   public String getEmpId() {
      return empId;
   }

   public void setEmpId(String empId) {
      this.empId = empId;
   }

   public String getEmpAddress() {
      return empAddress;
   }

   public void setEmpAddress(String empAddress) {
      this.empAddress = empAddress;
   }

   public double getSalary() {
      return salary;
   }

   public void setSalary(double salary) {
      this.salary = salary;
   }

   @Override
   public String toString() {
      return "Employee [empName=" + empName + ", empId=" + empId + ", empAddress=" + empAddress + ", salary=" + salary
            + "]";
   }
}

EmployeeConfig.java

package com.ashok.spring.core.bean.javabasedconfig.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.ashok.spring.core.bean.javabasedconfig.beans.Employee;

/**
 * 
 * @author Ashok Kumar
 *
 */
@Configuration
public class EmployeeConfig {
   @Bean
   public Employee getEmployeeConfig() {
      return new Employee();
   }
}

Client Application 

package com.ashok.spring.core.bean.javabasedconfig.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.ashok.spring.core.bean.javabasedconfig.beans.Employee;
import com.ashok.spring.core.bean.javabasedconfig.config.EmployeeConfig;

/**
 * 
 * @author Ashok Kumar
 *
 */
public class TestSpringApplication {
   @SuppressWarnings("resource")
   public static void main(String[] args) {
      ApplicationContext context = new AnnotationConfigApplicationContext(EmployeeConfig.class);
      Employee emp = (Employee) context.getBean("getEmployeeConfig");
      emp.setEmpName("Ashok Kumar");
      emp.setEmpAddress("Bhimavaram");
      emp.setEmpId("E0087");
      emp.setSalary(45000);
      System.out.println(emp);
   }
}
Bean Definition
Scroll to top