Recent Posts

Saturday, 8 June 2019

Bean Definition

     Bean is a Software Reusable Component, it is a normal java class contains properties and the corresponding setXXX(-) and getXXX() methods and which are created and managed by IOC Container in Spring Framework.
Rules and Regulations to write Bean classes
1. Bean classes must be POJO classes, they must not extend or implement any predefined Library except java.io.Serializable marker interface.
2. Bean must be declared as "public", "Non-abstract" and "non-final".
     The main intention of declaring bean class as "public" is to make available bean class scope to IOC Container in order to create objects. The main intention to declare bean class as "Non-abstract" is to allow to create object. The main intention to declare bean classes as "Non-final" is to extend one bean class to another bean class in order to improve reusability.
3. In Bean classes, we have to declare all properties as "private" and all behaviors as "public", it will improve "Encapsulation".
4. If we want to provide any constructor in bean class then provide a constructor, it must be 0-arg constructor and "public" constructor, because, IOC Container will search and execute public and 0-arg constructor while instantiating bean.
     If we want to use Beans in Spring applications then we must configure that bean classes in spring beans configuration file, because, IOC Container will recognize and create Bean objects by getting bean class details from beans configuration file only. There are 3 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 beans configuration file we have to use the following xml tags.
<beans>
   <bean id="--" name="--" class="--" scope="--">
      <property name="--" value="--"/>
   </bean>
</beans>
     Where <beans> tag is root tag in beans configuration file. Where <bean> tag is able to provide configuration details of a particular bean class. Where "class" attribute in <bean> is able to provide fully qualified name of the bean class.
     Where <property> attribute is able to 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 is able to take exactly one identity to the bean object, it will not allow more than one identity.
'name' attribute in <bean> tag is able to allow more than one identity name to the bean object, where in multiple values only first value is treated as the actual bean identity and 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" attribuite 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 are able to define scopes to the data by using the access modifiers like public, protected, <default> and private. Similarly, in 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 default scope in Spring applications.
☀ If we use this scope to the bean then IOC Container will create Single Bean object for single bean definition in Spring config file.
☀ This approach will return the same bean object for every time requesting bean object.
☀ When we request bean object first time then IOCContainer will create bean object and it will be stored in Cache memory, then, every time accessing 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 default Scope in Spring framework.
☀ In Spring applications, if we provide "prototype" scope in bean configuration file then IOC Container will create a new Bean object at each and every time of calling 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 useful in Standalone Applications [Spring Core Module], it will be used in Web applications which are prepared on the basis of Spring Web module.
☀ Request Scope is able to create a separate bean object for each and every request object.

4. Session Scope
☀ This Scope will be used web applications which are prepared on the basis of Spring web module and it is not applicable in Standalone Applications.
☀ Session Scope allows to create a separate bean object for each and every Session object in web applications.

5. GlobalSession Scope
☀ This scope is not useful in standard applications, it is useful in portlet applications which are prepared on the basis of Spring web module.
☀ Global Session scope allows to create a separate bean object for each and every portlet Session.

6. Application Scope
☀ This scope is not useful in standalone Applications, it is useful in web applications prepared on the basis of Spring web module.
☀ ApplicationScope allows to create a separate bean object for each and every ServletContext object.

7. Websocket Scope
☀ This scope is useful in web applications which are prepared on the basis of spring web module.
☀ websocket scope allows to create a separate bean object for single websocket lifecycle.
☀ If we use the scopes like request, session, globalSession, appplication, webSocket etc. in standalone applications which are prepared on the basis of spring core module then Container will rise an exception like "java.lang.IllegalStateException".

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

2. Java Based Configuration
     In Spring, up to Spring2.4 version Spring beans configuration file is mandatory to configure bean classes and their metadata, but, Right from Spring3.x version Spring beans configuration file is optional, because, Spring3.x version has provided Java Based Configuration as replacement for XML documents.
     If we want to use Java Based Configuration as an alternative to Spring beans configuration file in Spring applications then we have to 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);
   }
}

Next Tutorial : Bean Life Cycle

Previous Tutorial : Spring IOC Containers
 

1 comment: