Monday, 6 February 2017

Spring: Circular Dependency problem

What is Circular Dependency Problem?
Circular dependency is a relation between two or more modules which either directly or indirectly depend on each other to function properly. Let me explain with an example.

Suppose there are two classes A and B. A is dependent on B and B is dependent on A.

As you see the constructor of class ‘A’, it initialize object of class B, that means A is dependent on B.

As you see the constructor of class ‘B’, it initialize object of class A, that means B is dependent on A.

A is dependent on B and B is dependent on A. This is called circular dependency problem.

What happen if you try to instantiate class A (or) B?
Let us try to define object for class A, the constructor of class A calls the constructor of class B. The constructor of class B calls the constructor of class A. This is an infinite recursion call, finally application end up in  StackOverflowError. Spring throws ‘BeanInstantiationException’ in case of circular dependency.

A.java
package com.sample.pojo;

public class A {
 private B b;

 public A() {
  this.b = new B();
 }
}

B.java
package com.sample.pojo;

public class B {
 private A a;

 public B() {
  this.a = new A();
 }
}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="a" name="objA" class="com.sample.pojo.A" />

</beans>

HelloWorld.java

package com.sample.test;

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

import com.sample.pojo.A;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  A obj1 = context.getBean("a", A.class);

  System.out.println(obj1);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you will end up in following error.

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'a' defined in class path resource [myConfiguration.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.sample.pojo.A]: Constructor threw exception; nested exception is java.lang.StackOverflowError
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1110)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1055)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
 at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
 at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
 at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
 at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
 at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
 at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
 at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
 at com.sample.test.HelloWorld.main(HelloWorld.java:10)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.sample.pojo.A]: Constructor threw exception; nested exception is java.lang.StackOverflowError
 at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
 at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1103)
 ... 13 more
Caused by: java.lang.StackOverflowError
 at com.sample.pojo.B.<init>(B.java:6)
 at com.sample.pojo.A.<init>(A.java:7)
 at com.sample.pojo.B.<init>(B.java:7)
 at com.sample.pojo.A.<init>(A.java:7)
 at com.sample.pojo.B.<init>(B.java:7)
 at com.sample.pojo.A.<init>(A.java:7)
 at com.sample.pojo.B.<init>(B.java:7)
 at com.sample.pojo.A.<init>(A.java:7)
 at com.sample.pojo.B.<init>(B.java:7)
 at com.sample.pojo.A.<init>(A.java:7)
 at com.sample.pojo.B.<init>(B.java:7)
 at com.sample.pojo.A.<init>(A.java:7)
 at com.sample.pojo.B.<init>(B.java:7)
 at com.sample.pojo.A.<init>(A.java:7)
 at com.sample.pojo.B.<init>(B.java:7)

How to resolve Circular dependency?
There are two ways to resolve this problem.
a.   Removing the dependency from constructor definition
b.   Point the circular dependency to current object

Removing the dependency from constructor definition
Define the dependencies using setter methods like below.


A.java

public class A {
 private B b;

 public A() {

 }

 public void setB(B b) {
  this.b = b;
 }

}

B.java

public class B {
 private A a;

 public B() {

 }

 public void setA(A a) {
  this.a = a;
 }

}

Point the circular dependency to current object

Update classes A and B like below.

public class A {
 private B b;

 public A() {
  b = new B(this);
 }

}


public class B {
 private A a;

 public B(A a) {
  this.a = a;
 }

}



Previous                                                 Next                                                 Home

Sunday, 5 February 2017

Spring: Injecting properties

In my previous post, I explained constructor based dependency injection. Spring provides another way also, where you can inject properties of bean using setter methods.
public class Employee {
 private int id;
 private String firstName;
 private String lastName;
}

We can inject properties to Employee class like below.
 <bean id="1" name="Krishna" class="com.sample.pojo.Employee">
  <property name="id" value="543216" />
  <property name="lastName" value="Gurram" />
  <property name="firstName" value="Hari Krishna" />
 </bean>


Following is the complete working application.


Employee.java
package com.sample.pojo;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

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

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append("]");
  return builder.toString();
 }

}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="1" name="Krishna" class="com.sample.pojo.Employee">
  <property name="id" value="543216" />
  <property name="lastName" value="Gurram" />
  <property name="firstName" value="Hari Krishna" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

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

import com.sample.pojo.Employee;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Employee employee = context.getBean("Krishna", Employee.class);

  System.out.println(employee);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Output
Employee [id=543216, firstName=Hari Krishna, lastName=Gurram]




Previous                                                 Next                                                 Home

Friday, 3 February 2017

Spring: Inject other beans in constructor arguments

In my previous post, I explained how to inject arguments to a constructor. There are cases, where a constructor takes other objects as arguments, By using ‘constructor-arg’ tag and ‘ref’ attribute you can specify the beans to inject as constructor arguments.
 <bean id="bookOfSecrets" class="com.sample.pojo.Book">
  <constructor-arg name="author" ref="osho" />
  <constructor-arg name="title" value="The Book Of Secrets" />
  <constructor-arg name="noOfPages" value="1152" />
  <constructor-arg name="price" value="452" />
 </bean>

Bean ‘osho’ is referenced in the bean with id ‘bookOfSecrets’.

Following is the complete working application.
Author.java
package com.sample.pojo;

public class Author {
 private String firstName;
 private String lastName;
 private String dateOfBirth;
 private String country;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getDateOfBirth() {
  return dateOfBirth;
 }

 public void setDateOfBirth(String dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
    .append(", dateOfBirth=").append(dateOfBirth).append(", country=").append(country).append("]");
  return builder.toString();
 }

}

Book.java
package com.sample.pojo;

public class Book {
 private String title;
 private int noOfPages;
 private float price;
 private Author author;

 Book(Author author, String title, int noOfPages, float price) {
  this.author = author;
  this.title = title;
  this.noOfPages = noOfPages;
  this.price = price;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public int getNoOfPages() {
  return noOfPages;
 }

 public void setNoOfPages(int noOfPages) {
  this.noOfPages = noOfPages;
 }

 public float getPrice() {
  return price;
 }

 public void setPrice(float price) {
  this.price = price;
 }

 public Author getAuthor() {
  return author;
 }

 public void setAuthor(Author author) {
  this.author = author;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Book [title=").append(title).append(", noOfPages=").append(noOfPages).append(", price=")
    .append(price).append(", author=").append(author).append("]");
  return builder.toString();
 }

}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="osho" class="com.sample.pojo.Author">
  <property name="firstName" value="Chandra Mohan" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

 <bean id="bookOfSecrets" class="com.sample.pojo.Book">
  <constructor-arg name="author" ref="osho" />
  <constructor-arg name="title" value="The Book Of Secrets" />
  <constructor-arg name="noOfPages" value="1152" />
  <constructor-arg name="price" value="452" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

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

import com.sample.pojo.Book;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Book myBook = context.getBean("bookOfSecrets", Book.class);

  System.out.println(myBook);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run ‘HelloWorld.java’, you can able to see following output.
Book [title=The Book Of Secrets, noOfPages=1152, price=452.0, author=Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]]


Previous                                                 Next                                                 Home

Thursday, 2 February 2017

Spring: Constructor based dependency injection

In this post, I am going to explain how to pass arguments to constructor. For example, following is my constructor definition.

         public Employee(int id, String firstName, String lastName){
                 this.id = id;
                 this.firstName = firstName;
                 this.lastName = lastName;
         }

By using ‘constructor-arg’ tag, you can pass arguments to the constructor.
There are three ways to pass values to constructor.
a.   Passing the arguments in the same way they defined in the constructor.
b.   Passing the arguments using the index value. In the above case, argument id has index 0, firstName has index 1, lastName has index 2.
c.    Passing the arguments using the name of the argument.

a. Passing the arguments in the same order they defined in the constructor.
<bean id="529" name="hari" class="com.sample.pojo.Employee">
 <constructor-arg type="int" value="529" />
 <constructor-arg type="java.lang.String" value="Hari Krishna" />
 <constructor-arg type="java.lang.String" value="Gurram" />
</bean>


b. Passing the arguments using the index value.
<bean id="530" name="sudhir" class="com.sample.pojo.Employee">
 <constructor-arg index="2" value="Sami" />
 <constructor-arg index="0" value="530" />
 <constructor-arg index="1" value="Sudhir Kumar" />
</bean>

c. Passing the arguments using the name of the argument.
<bean id="531" name="kiran" class="com.sample.pojo.Employee">
 <constructor-arg name="lastName" value="Darsi" />
 <constructor-arg name="id" value="531" />
 <constructor-arg name="firstName" value="Kiran Kumar" />
</bean>


Following is the complete working application.

Employee.java
package com.sample.pojo;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;

 public Employee(int id, String firstName, String lastName) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public int getId() {
  return id;
 }

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

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append("]");
  return builder.toString();
 }

}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="529" name="hari" class="com.sample.pojo.Employee">
  <constructor-arg type="int" value="529" />
  <constructor-arg type="java.lang.String" value="Hari Krishna" />
  <constructor-arg type="java.lang.String" value="Gurram" />
 </bean>


 <bean id="530" name="sudhir" class="com.sample.pojo.Employee">
  <constructor-arg index="2" value="Sami" />
  <constructor-arg index="0" value="530" />
  <constructor-arg index="1" value="Sudhir Kumar" />
 </bean>


 <bean id="531" name="kiran" class="com.sample.pojo.Employee">
  <constructor-arg name="lastName" value="Darsi" />
  <constructor-arg name="id" value="531" />
  <constructor-arg name="firstName" value="Kiran Kumar" />
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

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

import com.sample.pojo.Employee;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Employee employee1 = context.getBean("hari", Employee.class);
  Employee employee2 = context.getBean("sudhir", Employee.class);
  Employee employee3 = context.getBean("kiran", Employee.class);

  System.out.println(employee1);
  System.out.println(employee2);
  System.out.println(employee3);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you can able to see following output.
Employee [id=529, firstName=Hari Krishna, lastName=Gurram]
Employee [id=530, firstName=Sudhir Kumar, lastName=Sami]
Employee [id=531, firstName=Kiran Kumar, lastName=Darsi]




Previous                                                 Next                                                 Home

Wednesday, 1 February 2017

Spring: Aliasing a bean

In my previous post, I explained how to access bean with multiple names. There is also another way, by using aliases, you can refer a bean using other name.

Syntax
<alias name="fromName" alias="toName"/>

Bean with name fromName can be referred by using the alias name toName.

Example
 <bean id="author1" name="Osho" class="com.sample.pojo.Author">
  <property name="firstName" value="Chandra Mohan" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

 <alias name="Osho" alias="Rajneesh" />
 <alias name="Osho" alias="Chandra Mohan Jain" />

You can refer the bean named “Osho” with ‘Ranjneesh” (or) “Chandra Mohan Jain”.

Following is the complete working application.

Author.java
package com.sample.pojo;

public class Author {
 private String firstName;
 private String lastName;
 private String dateOfBirth;
 private String country;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getDateOfBirth() {
  return dateOfBirth;
 }

 public void setDateOfBirth(String dateOfBirth) {
  this.dateOfBirth = dateOfBirth;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Author [firstName=").append(firstName).append(", lastName=").append(lastName)
    .append(", dateOfBirth=").append(dateOfBirth).append(", country=").append(country).append("]");
  return builder.toString();
 }

}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="author1" name="Osho" class="com.sample.pojo.Author">
  <property name="firstName" value="Chandra Mohan" />
  <property name="lastName" value="Jain" />
  <property name="dateOfBirth" value="11 December 1931" />
  <property name="country" value="India" />
 </bean>

 <alias name="Osho" alias="Rajneesh" />
 <alias name="Osho" alias="Chandra Mohan Jain" />

</beans>


HelloWorld.java
package com.sample.test;

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

import com.sample.pojo.Author;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Author author1 = context.getBean("Rajneesh", Author.class);
  Author author2 = context.getBean("Osho", Author.class);
  Author author3 = context.getBean("Chandra Mohan Jain", Author.class);

  System.out.println(author1);
  System.out.println(author2);
  System.out.println(author3);

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you can able to see following output.
Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]
Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]
Author [firstName=Chandra Mohan, lastName=Jain, dateOfBirth=11 December 1931, country=India]



Previous                                                 Next                                                 Home