Spring Bean Life Cycle and Callbacks

The Spring Framework provide several call back methods to created a bean and some method to be destroy the bean in the Spring IoC Container.
Spring Bean Life Cycle

@ImageSource-Youtube

The Spring Framework provides several marker interfaces to change the behavior of your bean in the container; they include InitializingBean and DisposableBean. Implementing these interfaces will result in the container calling afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction.
The life cycle of a Spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.

Though, there is lists of the activities that take place behind the scenes between the time of bean Instantiation and its destruction, but this chapter will discuss only two important bean lifecycle callback methods which are required at the time of bean initialization and its destruction.

Beans can be notified after creation and all properties are set, and before they are destroyed and removed from the bean container. This involves specifying the callback method to be invoked by the container. This is done in XML by specifying attributes init-method=”myinit”, for the initialization callback, and destroy-method=”mydestroy”, for the destroy callback. “myinit” and “cleanUp” are names of instance methods in the bean class.

Initialization callbacks:
Implementing the org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean are set by the container. The InitializingBean interface specifies exactly one method:
org.springframework.beans.factory.InitializingBean interface  provide Initialization callbacks method as given below..
void afterPropertiesSet() throws Exception
Now we can implements above interface and do some initialization functionality with in this method. As below..
public class Triangle implements InitializingBean
{
     @Override
     public void afterPropertiesSet() throws Exception
     {
       //To do some initialization works here
       System.out.println("InitializingBean init method is called for Triangle");
     }
}
Generally, the use of the InitializingBean interface can be avoided (and is discouraged since it unnecessarily couples the code to Spring). A bean definition provides support for a generic initialization method to be specified. In the case of XML-based configuration metadata, this is done using the ‘init-method’ attribute. For example, the following definition:
In the case of XML-based configuration metadata, we can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example:
<bean class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Triangle" id="triangle" init-method="myInit"></bean>

Now following has myInit method in class.
public class Triangle
{
  public void myInit()
  {
     //To do some initialization works here
     System.out.println("My init method is called for Triangle");
  }
}
Now using Java annotations can also be used to declare life-cycle callbacks.
public class Triangle
{
  //init callback
  @PostConstruct
  public void myInit()
  {
     //To do some initialization works here
     System.out.println("My init method is called for Triangle");
  }
}
Destruction callbacks:
Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies one method:
void destroy() throws Exception
Now we can implements above interface and do some Destruction functionality with in this method. As below..
public class Triangle implements DisposableBean 
{
     @Override
     public void destroy() throws Exception
     {
       //To do some Destruction works here
       System.out.println("DisposableBean destroy method is called for Triangle");
     }
}
Generally, the use of the DisposableBean marker interface can be avoided (and is discouraged since it unnecessarily couples the code to Spring). A bean definition provides support for a generic destroy method to be specified. When using XML-based configuration metadata this is done via the ‘destroy-method’ attribute on the . For example, the following definition:
In the case of XML-based configuration metadata, we can use the destroy-method attribute to specify the name of the method that has a void no-argument signature. For example:
<bean class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Triangle" destroy-method="cleanUp" id="triangle"></bean>
Now following has cleanUp method in class.
public class Triangle
{
  public void cleanUp()
  {
     //To do some Destruction works here
     System.out.println("cleanUp method is called for Triangle");
  }
}
Now using Java annotations can also be used to declare life-cycle callbacks.
public class Triangle
{
  //destroy callback
  @PreDestroy
  public void myInit()
  {
     //To do some Destruction works here
     System.out.println("cleanUp method is called for Triangle");
  }
}

If you are using Spring’s IoC container in a non-web application environment; for example, in a rich client desktop environment; you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released.

It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method.
Lets see the Example:

Triangle.java

package com.dineshonjava.sdnext.callbackLifecycle.tutorial;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;


public class Triangle implements InitializingBean, DisposableBean
{
 private Point pointA;
 private Point pointB;
 private Point pointC;
 /**
  * @param pointA the pointA to set
  */
 public void setPointA(Point pointA) {
  this.pointA = pointA;
 }

 /**
  * @param pointB the pointB to set
  */
 public void setPointB(Point pointB) {
  this.pointB = pointB;
 }

 /**
  * @param pointC the pointC to set
  */
 public void setPointC(Point pointC) {
  this.pointC = pointC;
 }

 public void draw()
 {
System.out.println("PointA is ("+pointA.getX()+", "+pointA.getY()+")");
System.out.println("PointB is ("+pointB.getX()+", "+pointB.getY()+")");
System.out.println("PointC is ("+pointC.getX()+", "+pointC.getY()+")");
 }

 @Override
 public void afterPropertiesSet() throws Exception
 {
System.out.println("InitializingBean init method is called for Triangle");
 }

 @Override
 public void destroy() throws Exception
 {
System.out.println("DisposableBean destroy method is called for Triangle");
 }
 
 public void myInit()
 {
   System.out.println("My init method is called for Triangle");
 }
 
 public void cleanUp()
 {
   System.out.println("cleanUp method is called for Triangle");
 }
}

Point.java

package com.dineshonjava.sdnext.callbackLifecycle.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}
Following is the configuration file Spring.xml required for init and destroy methods.

Spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
  
<bean autowire="byName" class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Triangle" destroy-method="cleanUp" id="triangle" init-method="myInit">
</bean>

<bean class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point" id="pointA">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point" id="pointB">
   <property name="x" value="-20"></property>
   <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point" id="pointC">
  <property name="x" value="20"></property>
  <property name="y" value="0"></property>
</bean>
</beans>
Once you are done with creating source and bean configuration files, let us run the following application. If everything is fine with your application, this will print the following message:
package com.dineshonjava.sdnext.callbackLifecycle.tutorial;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
context.registerShutdownHook();
Triangle triangle = (Triangle) context.getBean("triangle");
triangle.draw();
 }

}
Output:
Jul 1, 2012 2:48:33 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sun Jul 01 14:48:33 IST 2012]; root of context hierarchy
Jul 1, 2012 2:48:33 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jul 1, 2012 2:48:33 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1543c88: defining beans [triangle,pointA,pointB,pointC]; root of factory hierarchy

InitializingBean init method is called for Triangle
My init method is called for Triangle
PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)

Jul 1, 2012 2:48:33 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sun Jul 01 14:48:33 IST 2012]; root of context hierarchy

DisposableBean destroy method is called for Triangle
cleanUp method is called for Triangle

Default initialization and destroy methods: If you have too many beans having initialization and or destroy methods with the same name, you don’t need to declare init-method and destroy-method on each individual bean. Instead framework provides the flexibility to configure such situation using default-init-method and default-destroy-method attributes on the <beans> element as follows:
spring.xml
<beans default-destroy-method="cleanUp" default-init-method="myInit" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
  
<bean autowire="byName" class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Triangle" id="triangle">
</bean>
  
<bean class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point" id="pointA">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>
<bean class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point" id="pointB">
  <property name="x" value="-20"></property>
  <property name="y" value="0"></property>
</bean>
<bean class="com.dineshonjava.sdnext.callbackLifecycle.tutorial.Point" id="pointC">
  <property name="x" value="20"></property>
  <property name="y" value="0"></property>
</bean>
</beans>
Now again run the application with above the configuration file we will get the following output:
Output:
Jul 1, 2012 2:58:00 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sun Jul 01 14:58:00 IST 2012]; root of context hierarchy
Jul 1, 2012 2:58:00 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jul 1, 2012 2:58:01 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1543c88: defining beans [triangle,pointA,pointB,pointC]; root of factory hierarchy

InitializingBean init method is called for Triangle
My init method is called for Triangle
PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)
DisposableBean destroy method is called for Triangle
cleanUp method is called for Triangle

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example
In Next Chapter we will discuss about to Writing BeanPostProcessor in Spring.
                                          
                                                        << Previous || Next >> 

Spring Bean Definition Inheritance Example

Spring Bean definition inheritance-. A bean definition potentially contains a large amount of configuration information, including container specific information and constructor arguments and property values. A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed. Using parent and child bean definitions can save a lot of typing. Effectively, this is a form of templating.
Spring Bean Definition Inheritance

@ImageSource-Slideshare.net

If you work with an ApplicationContext interface programmatically, child bean definitions are represented by the ChildBeanDefinition class. Most users do not work with them on this level, instead configuring bean definitions declaratively in something like the ClassPathXmlApplicationContext

When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute.

Spring Bean definition inheritance has nothing to do with Java class inheritance but inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit required configuration from the parent bean.

Now the following example illustrate the bean definition inheritance with triangle classes and its parents classes.

Triangle.java

package com.dineshonjava.sdnext.beanDefInherit.tutorial;

public class Triangle
{
 private Point pointA;
 private Point pointB;
 private Point pointC;
 /**
  * @param pointA the pointA to set
  */
 public void setPointA(Point pointA) {
  this.pointA = pointA;
 }

 /**
  * @param pointB the pointB to set
  */
 public void setPointB(Point pointB) {
  this.pointB = pointB;
 }

 /**
  * @param pointC the pointC to set
  */
 public void setPointC(Point pointC) {
  this.pointC = pointC;
 }

 public void draw()
 {
System.out.println("PointA is ("+pointA.getX()+", "+pointA.getY()+")");
System.out.println("PointB is ("+pointB.getX()+", "+pointB.getY()+")");
System.out.println("PointC is ("+pointC.getX()+", "+pointC.getY()+")");
 }
}

Point.java

package com.dineshonjava.sdnext.beanDefInherit.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}
Following is the configuration file spring.xml where we defined “parentTriangle” bean which has one property “pointA”. Next there are two beans “triangle1” bean and “triangle2” bean has been defined as a child of “parentTriangle” bean by using parent attribute. The child beans inherits “pointA” property as is, and overrides “pointA” property and introduces two more properties “pointB” and “pointC.

Spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
  
<bean class="com.dineshonjava.sdnext.beanDefInherit.tutorial.Triangle" id="parentTriangle">
    <property name="pointA" ref="pointA"></property>
</bean>
<bean class="com.dineshonjava.sdnext.beanDefInherit.tutorial.Triangle" id="triangle1" parent="parentTriangle">
   <property name="pointB" ref="pointB"></property>
   <property name="pointC" ref="pointC"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.beanDefInherit.tutorial.Triangle" id="triangle2" parent="parentTriangle">
   <property name="pointB" ref="pointB"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.beanDefInherit.tutorial.Point" id="pointA">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.beanDefInherit.tutorial.Point" id="pointB">
  <property name="x" value="-20"></property>
  <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.beanDefInherit.tutorial.Point" id="pointC">
  <property name="x" value="20"></property>
  <property name="y" value="0"></property>
</bean>
</beans>
Once you are done with creating source and bean configuration files, let us run the following application. If everything is fine with your application, this will print the following message:

Point.java

package com.dineshonjava.sdnext.beanDefInherit.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle = (Triangle) context.getBean("triangle1");
triangle.draw();
 }
}
Now we get the following message:
Output:
Jul 1, 2012 1:43:35 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Sun Jul 01 01:43:35 IST 2012]; root of context hierarchy
Jul 1, 2012 1:43:35 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jul 1, 2012 1:43:36 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@14c1103: defining beans [parentTriangle,triangle1,triangle2,pointA,pointB,pointC]; root of factory hierarchy

PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)

If you observed here, we did not pass “pointA” while creating “triangle1” bean, but it got passed because of Bean Definition Inheritance.

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

In Next Chapter we will discuss about Bean Lifecycle and Callbacks in Spring.
                                          
                                                        << Previous || Next >> 

Using ApplicationContextAware in Spring

In this chapter we will show you a short hint how you can access your Spring-ApplicationContext from everywhere in your Application.

We’ll provide our beans with access to the ApplicationContext object by implementing the ApplicationContextAware interface. We’ll also use BeanNameAware interface to get the name of the bean configured in the Spring XML.

ApplicationContextAware in Spring

@ImageSource-Slideshare.net

WHY ApplicationContextAware?

Imagine we have an application (e.g. a web or swing-application) which we now want to be Spring-enabled. Ok we add the Spring libraries(spring.jar) and the Configuration-file(spring.xml) and create our Spring-beans. But there are still some old class-files which you can’t use in this way. These files still need access to the Spring-Honeypot where all the goodies exists and you don’t want to redesign your application.

First create the class “ApplicationContextProvider (Triangle class)”. This   class    implements    the ApplicationContextAware. A bean which implements the ApplicationContextAware-interface and is deployed into the context, will be called back on creation of the bean, using the interface’s setApplicationContext(…) method, and provided with a reference to the context, which may be stored for later interaction with the context.

In this tutorial you will see and example of using ApplicationContextAware. The ApplicationContextAware is used when an object required. 

Triangle.java

package com.dineshonjava.sdnext.contextAware.tutorial;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Triangle implements ApplicationContextAware, BeanNameAware
{
 private Point pointA;
 private Point pointB;
 private Point pointC;
 private ApplicationContext context = null;
 
 /**
  * @param pointA the pointA to set
  */
 public void setPointA(Point pointA) {
  this.pointA = pointA;
 }

 /**
  * @param pointB the pointB to set
  */
 public void setPointB(Point pointB) {
  this.pointB = pointB;
 }

 /**
  * @param pointC the pointC to set
  */
 public void setPointC(Point pointC) {
  this.pointC = pointC;
 }

 public void draw()
 {
System.out.println("PointA is ("+pointA.getX()+", "+pointA.getY()+")");
System.out.println("PointB is ("+pointB.getX()+", "+pointB.getY()+")");
System.out.println("PointC is ("+pointC.getX()+", "+pointC.getY()+")");
 }

 @Override
 public void setApplicationContext(ApplicationContext context) throws BeansException
 {
  this.context = context;
 }

 @Override
 public void setBeanName(String beanName)
 {
  System.out.println("Bean name is: "+beanName);
 }
}

Point.java

package com.dineshonjava.sdnext.contextAware.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}

spring.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 <bean autowire="byName" class="com.dineshonjava.sdnext.contextAware.tutorial.Triangle" id="triangle"></bean>
  
<bean class="com.dineshonjava.sdnext.contextAware.tutorial.Point" id="pointA">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.contextAware.tutorial.Point" id="pointB">
  <property name="x" value="-20"></property>
  <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.contextAware.tutorial.Point" id="pointC">
   <property name="x" value="20"></property>
   <property name="y" value="0"></property>
</bean>
</beans>

DrawingApp.java

package com.sdnext.contextAware.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle = (Triangle) context.getBean("triangle");
triangle.draw();
 }
}
Output:
Jun 30, 2012 3:28:54 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145d068: startup date [Sat Jun 30 15:28:54 IST 2012]; root of context hierarchy
Jun 30, 2012 3:28:55 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 30, 2012 3:28:55 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@f11404: defining beans [triangle,pointA,pointB,pointC]; root of factory hierarchy

Bean name is: triangle
PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)

What is Need for Using ApplicationContextAware in Application? In previous chapter we have seen that we create applicationcontext object via using configuration file(spring.xml) but we done this only one time of the applicationcontext object using configuration file (spring.xml) for entire application.

If we done one time creating applicationcontext object and also one time creating triangle bean through the getBean() method because its have “singleton” scope and beans pointA, pointB & pointC are also populated along with triangle bean only one time when triangle bean is initialized even though pointA, pointB & pointC are the prototype in scope.

After that we can not create as new bean pointA, pointB & pointC objects without creating triangle bean in the Triangle class or anywhere else except main app(DrawingApp.java).

And there are some situation we want to use applicationcontext object any where else like in bean class(in Triangle class). Suppose the Triangle bean need to applicationcontext object for some reasons.

Suppose If we want to create new beans pointA, pointB & pointC in triangle class then we have to declare  pointA, pointB & pointC beans as prototype bean scope. Now we have need to access applicationContext object in the triangle bean class so because of this     we     are       used ApplicationContextAware intreface and this interface is implements by the Triangle bean class for accessing applicationcontext object from    overriding    the    following     method    of            the ApplicationContextAware interface.

@override
public void setApplicationContext(ApplicationContext context) throws BeansException
{
  this.context = context;
}

In Next Chapter we will discuss about Bean Definition Inheritance in Spring in Application.

                                          
                                                        << Previous || Next >>

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

Prototype Bean Scope with Annotation

Prototype Bean Scope: If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.


Lets see with example which show the prototype scope of the ‘zeroPoint’ bean in the spring container.

Point.java

package com.dineshonjava.sdnext.beanscope.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}


spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
  
  <bean class="com.dineshonjava.sdnext.beanscope.tutorial.Point" id="zeroPoint" scope="prototype">
   <property name="x" value="0"></property>
   <property name="y" value="0"></property>
  </bean>
  
</beans>


DrawingApp.java

package com.dineshonjava.sdnext.beanscope.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

Point point1 = (Point) context.getBean("zeroPoint");
Point point2 = (Point) context.getBean("zeroPoint");
if(point1 == point2)
 System.out.println("In Singleton Demo >> Both are same objects values are.." +
     "n 1. point1= "+point1+" n 2. point2= "+point2);
else
  System.out.println("In Protptype Demo >> Both are different objects values are.." +
     "n 1. point1= "+point1+" n 2. point2= "+point2);
 }
}
Output:
Jun 28, 2012 9:10:46 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Thu Jun 28 21:10:46 IST 2012]; root of context hierarchy
Jun 28, 2012 9:10:46 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 28, 2012 9:10:46 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1543c88: defining beans [zeroPoint]; root of factory hierarchy

In Protptype Demo >> Both are different objects values are..
 1. point1= com.dineshonjava.sdnext.beanscope.tutorial.Point@d3d6f
 2. point2= com.dineshonjava.sdnext.beanscope.tutorial.Point@13c468a

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the above message: See the both address value of the object is different.

Bean scopes using annotation:


spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
<context:component-scan base-package="com.dineshonjava.sdnext.beanscope.tutorial">
</context:component-scan></beans>
Here component-scan element has attribute ‘base-package‘. base-package contain the base package of the Bean class.

base-package = “com.dineshonjava.sdnext.beanscope.tutorial”


Ponit.java

package com.dineshonjava.sdnext.beanscope.tutorial;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}

Annotation @Service:
Target : Class
Description:
Here @Service is streotype annotation which declared above the class name that means this class is a bean of the spring container.
In Spring container this bean recognized by the id “point” means that same as the class name except first letter of the class name is the small letter.
for example: class ‘Point‘ get as ‘point‘ bean
                    class ‘Circle‘ get as ‘circle‘ bean


Annotation @Scope:
Target : Class
Description:
Here @Scope is annotation which declared above the class name that define the scope the bean

 @Scope(“singleton”)
 @Scope(“prototype”)

DrawingApp.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dineshonjava.sdnext.beanscope.tutorial.Point;
/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Point point1 = (Point) context.getBean("point");
Point point2 = (Point) context.getBean("point");
if(point1 == point2)
  System.out.println("In Singleton Demo >> Both are same objects values are.." +
  "n 1. point1= "+point1+" n 2. point2= "+point2);
else
  System.out.println("In Protptype Demo >> Both are different objects values are.." +
  "n 1. point1= "+point1+" n 2. point2= "+point2);
 }
}
Output:

Jun 28, 2012 10:59:39 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@758fc9: startup date [Thu Jun 28 22:59:39 IST 2012]; root of context hierarchy
Jun 28, 2012 10:59:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 28, 2012 10:59:39 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@bb7759: defining beans [point,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
In Protptype Demo >> Both are different objects values are..
 1. point1= com.dineshonjava.sdnext.beanscope.tutorial.Point@d3d6f
 2. point2= com.dineshonjava.sdnext.beanscope.tutorial.Point@13c468a

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example
                              Bean Scope in The Spring

Singleton Bean Scope in Spring

Singleton Bean Scope: Scopes a single bean definition to a single object instance per Spring IoC container. This is the default behavior of the spring container

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.

We can say another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all 

Lets see with example which show the singleton scope of the ‘zeroPoint’ bean in the spring container.


Point.java

package com.dineshonjava.sdnext.beanscope.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}


spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd 
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
  
   
  <bean class="com.dineshonjava.sdnext.beanscope.tutorial.Point" id="zeroPoint" scope="singleton">
   <property name="x" value="0"></property>
   <property name="y" value="0"></property>
  </bean>
  
</beans>


DrawingApp.java

package com.dineshonjava.sdnext.beanscope.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

Point point1 = (Point) context.getBean("zeroPoint");
Point point2 = (Point) context.getBean("zeroPoint");
if(point1 == point2)
 System.out.println("In Singleton Demo >> Both are same objects values are.." +
     "n 1. point1= "+point1+" n 2. point2= "+point2);
else
  System.out.println("In Protptype Demo >> Both are different objects values are.." +
     "n 1. point1= "+point1+" n 2. point2= "+point2);
 }
}
Output:
Jun 28, 2012 9:10:46 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date [Thu Jun 28 21:10:46 IST 2012]; root of context hierarchy
Jun 28, 2012 9:10:46 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 28, 2012 9:10:46 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1543c88: defining beans [zeroPoint]; root of factory hierarchy

In Singleton Demo >> Both are same objects values are..
1. point1= com.dineshonjava.sdnext.beanscope.tutorial.Point@1198891
2. point2= com.dineshonjava.sdnext.beanscope.tutorial.Point@1198891

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the above message: See the both address value of the object is same.
Bean scopes using annotation:


spring.xml

<beans xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:security="http://www.springframework.org/schema/security" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans">
  
<context:component-scan base-package="com.dineshonjava.sdnext.beanscope.tutorial">
</context:component-scan></beans>
Here component-scan element has attribute ‘base-package‘. base-package contain the base package of the Bean class.

base-package = “com.dineshonjava.sdnext.beanscope.tutorial”


Ponit.java

package com.dineshonjava.sdnext.beanscope.tutorial;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("singleton")
public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}

Annotation @Service:
Target : Class
Description:
Here @Service is streotype annotation which declared above the class name that means this class is a bean of the spring container.
In Spring container this bean recognized by the id “point” means that same as the class name except first letter of the class name is the small letter.
for example: class ‘Point‘ get as ‘point‘ bean
                    class ‘Circle‘ get as ‘circle‘ bean

Annotation @Scope:
Target : Class
Description:
Here @Scope is annotation which declared above the class name that define the scope the bean

 @Scope(“singleton”)
 @Scope(“prototype”)

DrawingApp.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dineshonjava.sdnext.beanscope.tutorial.Point;
/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Point point1 = (Point) context.getBean("point");
Point point2 = (Point) context.getBean("point");
if(point1 == point2)
  System.out.println("In Singleton Demo >> Both are same objects values are.." +
  "n 1. point1= "+point1+" n 2. point2= "+point2);
else
  System.out.println("In Protptype Demo >> Both are different objects values are.." +
  "n 1. point1= "+point1+" n 2. point2= "+point2);
 }
}
Output:
Jun 28, 2012 10:22:04 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145d068: startup date [Thu Jun 28 22:22:04 IST 2012]; root of context hierarchy
Jun 28, 2012 10:22:04 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 28, 2012 10:22:04 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1cbfe9d: defining beans [point,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy

In Singleton Demo >> Both are same objects values are..
1. point1= com.dineshonjava.sdnext.beanscope.tutorial.Point@84da23
2. point2= com.dineshonjava.sdnext.beanscope.tutorial.Point@84da23

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example
                              Bean Scope in The Spring

Spring Autowiring by AutoDetect

In Spring “Autowiring by AutoDetect means” If a default constructor is found, uses “constructor“; Otherwise, uses “byType“. In this case, since there is a default constructor in “Circle” class, so, Spring auto wired it via constructor method – “public Circle(Point center)”.
For example, if “autowiring by autodetect“. Auto wiring the “center” bean into “circle“, via constructor or  by type, Its based on the implementation of Circle bean. Spring will find the “center” in current container and wire it automatically one of constructor or  by type.

You can enable this feature via autowire=”autodetect” like below :

With autowire by autodetectenabled, you do not need to declares the property tag anymore.

<bean autowire="autodetect" class="com.dineshonjava.sdnext.autoWiring.tutorial.Circle" id="circle">
  </bean>
 <bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="center">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
 </bean>

1.See AutoDetect – by Constructor Example
If a default constructor is supplied, auto detect will chooses wire by constructor.


Circle.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

public class Circle
{
 private Point center;
  
 /**
  * USING CONSTRUCTOR
  * @param center the center to set
  * autowiring by constructor
  */
 public Center(Point center) {
  this.center = center;
 }

/**
  * USING SETTER
  * @param center the center to set
  * autowiring by type
  */
 public setCenter(Point center) {
  this.center = center;
 }
 
public void draw()
 {
  System.out.println("Center of circle is ("+center.getX()+", "+center.getY()+")");
 }
}

2.See AutoDetect – by Type Example
If a default constructor is not found, auto detect will chooses wire by type.


Circle.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

public class Circle
{
 private Point center;
  
 /**
  * USING SETTER ONLY
  * @param center the center to set
  * autowiring by type
  */
 public setCenter(Point center) {
  this.center = center;
 }
 
public void draw()
 {
  System.out.println("Center of circle is ("+center.getX()+", "+center.getY()+")");
 }
}

Point.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}


spring.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean autowire="constructor" class="com.dineshonjava.sdnext.autoWiring.tutorial.Circle" id="circle">
  </bean>
 <bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="center">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
 </bean>
</beans>


DrawingApp.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  Circle circle = (Circle) context.getBean("circle");
  circle.draw();
 }
}

Now run this application and get following output on the console.

Output:
Jun 25, 2012 7:55:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 25, 2012 7:55:24 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1592174: defining beans [circle ,center]; root of factory hierarchy

Center of Circle is (0, 0)

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

Spring Autowiring by Constructor

In Spring “Autowiring by Constructor means” autowiring is actually autowiring by type it means if data type of a bean is same as the data type of other bean constructor argument, auto wire it.Spring container looks at the properties of the beans on which autowire attribute is set to constructorin the XML configuration file. It then tries to match and wire its properties with the beans defined by the same data type of constructor argument in the configuration file.
For example, if a “circle” bean exposes an “center” constructor argument of Point data type, Spring will find these “center” in current container and wire it automatically. And if no matching found, just do nothing.

You can enable this feature via autowire=”constructor” like below :

Normally, you wire the bean explicitly, via ref attribute like this :

<bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Circle" id="circle">
 <constructor-arg><ref bean="center"></ref>
  </constructor-arg></bean>  <bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="center">  <property name="x" value="0"></property>  <property name="y" value="0"></property>  </bean>  

With autowire by constructor enabled, you do not need to declares the property tag anymore. As long as the “center” beans are same data type as the constructor argument of “circle” bean, which is “center“, Spring will wire it automatically.

Lets see Exaple

Circle.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

public class Circle
{
 private Point center;
  
 /**
  * @param center the center to set
  */
 public Center(Point center) {
  this.center = center;
 }

 public void draw()
 {
  System.out.println("Center of circle is ("+center.getX()+", "+center.getY()+")");
 }
}


Point.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}


spring.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean autowire="constructor" class="com.dineshonjava.sdnext.autoWiring.tutorial.Circle" id="circle">
  </bean>
 <bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="center">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
 </bean>
</beans>


DrawingApp.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  Circle circle = (Circle) context.getBean("circle");
  circle.draw();
 }
}

Now run this application and get following output on the console.

Output:
Jun 25, 2012 7:55:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 25, 2012 7:55:24 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1592174: defining beans [circle ,center]; root of factory hierarchy

Center of Circle is (0, 0)

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

Spring Bean Scopes

In Spring we get the bean from the Spring container with some default configuration. Default behavior is that every beans in the Spring container are initialized when bean configuration file loaded to the JVM.  Whenever getBean is called container recognized the bean by given bean id and return that bean to the caller. One more default behavior is that every beans has only one instance in the spring container.
Bean Scope means which is used to decide which type of bean instance should be return from Spring container back to the caller. Basic Spring Bean Scopes are only two types-Singleton:(Default) Scopes a single bean definition to a single object instance per Spring IoC container. Prototype: Scopes a single bean definition to any number of object instances. But at web environment spring have three more scopes Request Scope: This scopes a bean definition to an HTTP request. Session Scope: This scopes a bean definition to an HTTP session. Global Session: Scopes a single bean definition to the lifecycle of a global HTTP Session.


Spring  Bean Scopes


We can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration.

Basic Spring Bean Scope are only two types are given below.
  1. Singleton Bean ScopeReturn a single bean instance per Spring IoC container
  2. Prototype Bean ScopeReturn a new bean instance each time when requested
1. Singleton Bean Scope: Scopes a single bean definition to a single object instance per Spring IoC container. This is the default behavior of the spring container.

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.

We can say another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

To define a singleton scope, you can set the scope property to singleton in the bean configuration file, as shown below:

<bean class="com.dineshonjava.sdnext.beanscope.Point" id="zeroPoint" scope="singleton">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>

See the singleton scope of bean with full example.

Using Annotation for Bean Scope:
@Service
@Scope("singleton")
public class Point
{
   private int x;
   private int y;
   
   public void setX(int x){
      this.x = x;
   }

   public void setY(int y){
      this.y = y;
   }
}

See the singleton scope of bean with full example.
NOTE : This singleton is differ from the singleton pattern in Java Class. Single pattern in java mean you can create the only one instance of a that class in JVM. But In spring singleton bean scope means every container can create only single bean in the Spring IoC Container but a JVM can have multiple Spring IoC Container so JVM can multiple beans rather than bean singleton bean scope.

Singleton  Bean Scopes

2. Prototype Bean Scope:
If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

To define a prototype scope, you can set the scope property to prototype in the bean configuration file, as shown below:

<bean class="com.dineshonjava.sdnext.beanscope.Point" id="zeroPoint" scope="prototype"><property name="x" value="0"></property>
  <property name="y" value="0"></property>
</bean>

See the full example of prototype bean scope with using the Annotation.

Using Annotation for Bean Scope:
@Service
@Scope("prototype")
public class Point
{
   private int x;
   private int y;
   
   public void setX(int x){
      this.x = x;
   }

   public void setY(int y){
      this.y = y;
   }
}

See the full example of prototype bean scope with using the Annotation.

Prototype Bean Scopes

There are three wen application aware bean scope are given below.

1. Request Scope: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
<bean class="com.dineshonjava.Point" id="point" scope="request"></bean>
2. Session Scope: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
<bean class="com.dineshonjava.Point" id="point" scope="session"></bean>
3. global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
<bean class="com.dineshonjava.Point" id="point" scope="globalSession"></bean>
The global session scope is similar to the standard HTTP Session scope (described immediately above), and really only makes sense in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared amongst all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are scoped (or bound) to the lifetime of the global portlet Session.
Please note that if you are writing a standard Servlet-based web application and you define one or more beans as having global session scope, the standard HTTP Session scope will be used, and no error will be raised.

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

In Next Chapter we will discuss about Application Context Aware in Spring in Application.
                                          
                                                        << Previous || Next >> 

Spring Autowiring by Type

In Spring “Autowire byType means” autowiring is done by property data type. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same data type in the configuration file.
Spring Autowiring by Type

For example, if a “circle” bean exposes an “center” property of Point data type, Spring will find these “center” in current container and wire it automatically. And if no matching found, just do nothing.
You can enable this feature via autowire=”byType” like below :

Normally, you wire the bean explicitly, via ref attribute like this :
<bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Circle" id="circle">
   <property name="center" ref="center"></property>
</bean>
<bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="center">
   <property name="x" value="0"></property>
   <property name="y" value="0"></property>
</bean>

With autowire by type enabled, you do not need to declares the property tag anymore. As long as the “center” beans are same data type as the property of “circle” bean, which is “center“, Spring will wire it automatically.

Lets see Exaple
Circle.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

public class Circle
{
 private Point center;
  
 /**
  * @param center the center to set
  */
 public void setCenter(Point center) {
  this.center = center;
 }

 public void draw()
 {
  System.out.println("Center of circle is ("+center.getX()+", "+center.getY()+")");
 }
}

Point.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}

spring.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean autowire="byType" class="com.dineshonjava.sdnext.autoWiring.tutorial.Circle" id="circle">
  </bean>
 <bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="center">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
 </bean>
</beans>

DrawingApp.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  Circle circle = (Circle) context.getBean("circle");
  circle.draw();
 }
}

Now run this application and get following output on the console.
Output:
Jun 25, 2012 7:55:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 25, 2012 7:55:24 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1592174: defining beans [circle ,center]; root of factory hierarchy

Center of Circle is (0, 0)

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example

Spring Autowiring by Name

In Spring “Autowire byName means” autowiring is done by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
Spring Autowiring by Name

For example, if a “triangle” bean exposes an “pointA, pointB & pointC” properties, Spring will find these point bean(“pointA, pointB & pointC“) in current container and wire it automatically. And if no matching found, just do nothing.

You can enable this feature via autowire=”byName” like below :

Normally, you wire the bean explicitly, via ref attribute like this :
<bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Triangle" id="triangle">
   <property name="pointA" ref="pointA"></property>
   <property name="pointB" ref="pointB"></property>
   <property name="pointC" ref="pointC"></property>
</bean>
<bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="pointA">
   <property name="x" value="0"></property>
   <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="pointB">
   <property name="x" value="-20"></property>
   <property name="y" value="0"></property>
</bean>
  
<bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="pointC">
   <property name="x" value="20"></property>
   <property name="y" value="0"></property>
</bean>

With autowire by name enabled, you do not need to declares the property tag anymore. As long as the “pointA, pointB & pointC” beans are same name as the property of “triangle” bean, which is “pointA, pointB & pointC”, Spring will wire it automatically.

Lets see Exaple
Triangle.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

public class Triangle 
{
 private Point pointA;
 private Point pointB;
 private Point pointC;
 
 /**
  * @param pointA the pointA to set
  */
 public void setPointA(Point pointA) {
  this.pointA = pointA;
 }

 /**
  * @param pointB the pointB to set
  */
 public void setPointB(Point pointB) {
  this.pointB = pointB;
 }

 /**
  * @param pointC the pointC to set
  */
 public void setPointC(Point pointC) {
  this.pointC = pointC;
 }

 public void draw()
 {
  System.out.println("PointA is ("+pointA.getX()+", "+pointA.getY()+")");
  System.out.println("PointB is ("+pointB.getX()+", "+pointB.getY()+")");
  System.out.println("PointC is ("+pointC.getX()+", "+pointC.getY()+")");
 }
}

Point.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

public class Point
{
 private int x;
 private int y;
 /**
  * @return the x
  */
 public int getX() {
  return x;
 }
 /**
  * @param x the x to set
  */
 public void setX(int x) {
  this.x = x;
 }
 /**
  * @return the y
  */
 public int getY() {
  return y;
 }
 /**
  * @param y the y to set
  */
 public void setY(int y) {
  this.y = y;
 }
}

spring.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean autowire="byName" class="com.dineshonjava.sdnext.autoWiring.tutorial.Triangle" id="triangle">
  </bean>
 <bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="pointA">
  <property name="x" value="0"></property>
  <property name="y" value="0"></property>
 </bean>
  
 <bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="pointB">
  <property name="x" value="-20"></property>
  <property name="y" value="0"></property>
 </bean>
  
 <bean class="com.dineshonjava.sdnext.autoWiring.tutorial.Point" id="pointC">
  <property name="x" value="20"></property>
  <property name="y" value="0"></property>
 </bean>
</beans>

DrawingApp.java

package com.dineshonjava.sdnext.autoWiring.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author Dinesh Rajput
 *
 */
public class DrawingApp 
{
 /**
  * @param args
  */
 public static void main(String[] args) 
 {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  Triangle triangle = (Triangle) context.getBean("triangle");
  triangle.draw();
 }
}

Now run this application and get following output on the console.
Output:
Jun 25, 2012 7:55:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 25, 2012 7:55:24 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1592174: defining beans [triangle,pointA,pointB,pointC]; root of factory hierarchy

PointA is (0, 0)
PointB is (-20, 0)
PointC is (20, 0)

Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example