Ad

Tuesday 31 March 2015

How to implement bubble sort algorithm in java

In this post we will see how to implement the bubble sort algorithm in java with a sample program.
Lets say there are N elements in the array to be sorted and the bubble sorting takes place by
  1.    Comparing  the adjacent elements in the array and swap its corresponding position if found greater.
  2.    Above step will be iterated upto the maximum of N -1 iteration until the array is fully sorted.
Below sample program will explain this in detail.

package test;

public class BubbleSortSample {

public static void main(String[] args) {
int[] arry = new int[] { 20, 3, 150, 5, 6, 78, 2, 123, 43, 45, 99, 1,
12 };
BubbleSortSample bubbleSort = new BubbleSortSample();
bubbleSort.sort(arry);
}

public void sort(int[] arry) {
printElements(arry);
int len = arry.length;
boolean isSwaped = false;
int temp = 0;
for (int i = 0; i < len; i++) {
isSwaped = false;
for (int j = 0; j < len - i - 1; j++) {
if (arry[j] > arry[j + 1]) {
temp = arry[j];
arry[j] = arry[j + 1];
arry[j + 1] = temp;
isSwaped = true;
}
}
printElements(arry);
if (!isSwaped) {
System.out.println("  Array has been fully sorted,hence rest of the iteration skipped");
break;
}
}
}

public void printElements(int[] arry) {
for (int i = 0; i < arry.length; i++) {
System.out.print(" " + arry[i]);
}
System.out.println();
}

}



When we run the above program,we will get this output

  20  3  150  5  6  78  2  123  43  45  99  1  12
  3  20  5  6  78  2  123  43  45  99  1  12  150
  3  5  6  20  2  78  43  45  99  1  12  123  150
  3  5  6  2  20  43  45  78  1  12  99  123  150
  3  5  2  6  20  43  45  1  12  78  99  123  150
  3  2  5  6  20  43  1  12  45  78  99  123  150
  2  3  5  6  20  1  12  43  45  78  99  123  150
  2  3  5  6  1  12  20  43  45  78  99  123  150
  2  3  5  1  6  12  20  43  45  78  99  123  150
  2  3  1  5  6  12  20  43  45  78  99  123  150
  2  1  3  5  6  12  20  43  45  78  99  123  150
  1  2  3  5  6  12  20  43  45  78  99  123  150
  1  2  3  5  6  12  20  43  45  78  99  123  150
  Array has been fully sorted,hence rest of the iteration skipped

Above output will show the array elements position at the end of each iteration and how the elements in the arrays were swapped.

Friday 27 March 2015

Lazy initialization of spring beans using lazy-init and default-lazy-init

In this post we will learn about the lazy initialization of spring beans using attribute lazy-init and default-lazy-init.By default spring container will create all the singleton bean at  container startup i.e when the spring container is loaded.This is necessary since if there is any error in creating the beans or setting the dependencies will be known to us at the container load time itself.But sometimes we don't need this behavior.We would like to create the bean only when it is requested and not at the container startup,thus reducing the container startup time.
 
Below code example will show how to lazy initialize the bean.

Employee- Spring bean which we will lazy initialize.
LazyInitDemo -  Main class which load the container and initializes the bean.
Studentcontext.xml - metadata configuration details for the spring container.

Employee.java

package bean;

public class Employee {

private String empId;

private String empName;

public Employee(String empId, String empName) {
this.empId = empId;
this.empName = empName;
System.out.println("Employee bean Created empId:" + empId + " empName:"
+ empName);
}

public String getEmpId() {
return empId;
}

public String getEmpName() {
return empName;
}

}

employeecontext.xml

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

<bean id="employee" class="bean.Employee" lazy-init="true">
<constructor-arg  name="empId" value="E01"/>
<constructor-arg  name="empName" value="Rahul"/>
</bean>

</beans>

As we can see in the application context file,we set the attribute lazy-init to true in the bean definition.This will make this bean to be create only when it is requested and not at the container load time.

LazyInitDemo.java

package bean;

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

public class LazyInitDemo {

public static void main(String[] args) {
ApplicationContext bf = new ClassPathXmlApplicationContext(
new String[] { "employeecontext.xml" });
System.out.println("Spring Container Laoded::");
System.out
.println("Going to request the employee bean from the container::");
Employee emp = bf.getBean("employee", Employee.class);
}
}

OUTPUT:

When we run LazyInitDemo class, we will get the below output

Spring Container Loaded::
Going to request the employee bean from the container::
Employee bean Created empId:E01 empName:Rahul


As we can see in the output,employee bean was not created at container loaded time and was created only when it was requested.

when we need all the beans defined in the application context to be lazy initialized,use the attribute default-lazy-init in the parent "beans" tag as shown below

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

<!--- bean 1 definition  -->

<!--- bean 2 definition  -->

</beans>

Thursday 26 March 2015

Spring bean Life Cycle - Callback Methods

In this post we will learn about the spring bean life cycle callback methods.Spring container provides the below two callback methods for the bean,so that the bean can perform certain actions during initialization or on destruction of the bean.
  • Initialization callback - After the bean is created by the container and the properties are set,the container will call this callback method.
  • Destruction callback - when the bean is about to destroyed i.e when the container is about to exit,the container will call this callback method.
In this post we will see how to configure this callback methods using the application context file (using attributes init-method and destroy-method).Below code example will explain this in detail.

Student - Spring bean class for which we will configure the callback methods.
CallbackDemo -  Main class which loads the container and initializes the bean.
Studentcontext.xml - Metadata configuration details for the spring container.

Student.java

package test;

public class Student {

private String name;

public String getName() {
return name;
}

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

public void init() {
System.out.println("Bean initialization callback invoked for student::"
+ this.name);
}

public void destroy() {
System.out.println("Bean Destruction callback invoked for student::"
+ this.name);
}
}

studentcontext.xml

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

<bean id="student" class="test.Student" init-method="init" destroy-method="destroy">
<property  name="name" value="Ram"/>
</bean>

</beans>

As we can see in the application context file,we used the below two attributes in the bean definition of student.
  • init-method - This will configure the initialization callback method(which is init) for the student bean
  • destroy-method - This will configure the destruction callback method(which is destroy) for the student bean
CallbackDemo.java

package test;

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

public class CallbackDemo {

public static void main(String[] args) {
AbstractApplicationContext  bf = new ClassPathXmlApplicationContext(
new String[] { "studentcontext.xml" });
bf.registerShutdownHook();
Student student= bf.getBean("student",Student.class);
}

}

We need to register the shutdownhook on the AbstractApplicationContext,so that the container will have the graceful shutdown and hence the corresponding destruction callback method on the bean will be called.

OUTPUT:

When we run the callbackDemo class, we will get the below output

Bean initialization callback invoked for student::Ram
Bean Destruction callback invoked for student::Ram

As we can see in the output,spring container
  • invoked the initialization callback(init method), after the properties in the bean are set.
  • invoked the destruction callback(destroy method) ,when the container is about to exit.

Wednesday 25 March 2015

depends-on attribute in spring with an example

In this post we will see the usage of depends-on attribute in spring.In spring if a bean has a dependency on another bean,we will declare one bean as the property of the other.But however in some cases the dependency will be indirect i.e we want a bean to be initialize only after a certain bean is initialized.depends-on attribute is used in this case. Below code example will explain this in detail.

BeanA,BeanB - Spring bean classes.Here we want the Spring container to initialize BeanB first and then the BeanA.
DependsDemo -  Main class which load the container and initializes the bean.
beancontext.xml - metadata configuration details for the spring container.

BeanA.java

package test;

public class BeanA {

private String id;

public BeanA(String id) {
this.id = id;
System.out.println("BeanA created::id=" + this.id);
}

public String getId() {
return id;
}

}

BeanB.java

package test;

public class BeanB {

private String id;

public BeanB(String id) {
this.id = id;
System.out.println("BeanB created::id=" + this.id);
}

public String getId() {
return id;
}

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


beancontext.xml

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

<bean id="beanA" class="test.BeanA" depends-on="beanB">
<constructor-arg  name="id" value="A01"/>
</bean>

<bean id="beanB" class="test.BeanB">
<constructor-arg  name="id" value="B01"/>
</bean>

</beans>


As we can see in the application context file,in the bean definition of BeanA we used depends-on attribute to specify its dependency on BeanB.Hence the spring container will initialize the BeanB first and then the bean BeanA.

DependsDemo.java

package test;

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

public class DependsDemo {

public static void main(String[] args) {
System.out.println("Initilaizing the container::");
ApplicationContext bf = new ClassPathXmlApplicationContext(
new String[] { "beancontext.xml" });
}

}

OUTPUT:

When we run DependsDemo class we will get the below output

Initilaizing the container::
BeanB created::id=B01
BeanA created::id=A01

As we can see in the output,spring container initialized the BeanB first and then the BeanA.

Monday 23 March 2015

class net.sf.cglib.core.DebuggingClassWriter has interface org.objectweb.asm.ClassVisitor as super class

In this post we see how to resolve the exception "java.lang.IncompatibleClassChangeError: class net.sf.cglib.core.DebuggingClassWriter has interface org.objectweb.asm.ClassVisitor as super class".The full stacktrace for this exception will look like below:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employee' defined in class path resource [aop.xml]: Initialization of bean failed; nested exception is java.lang.IncompatibleClassChangeError: class net.sf.cglib.core.DebuggingClassWriter has interface org.objectweb.asm.ClassVisitor as super class
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
           at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
           at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
           at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
           at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
           at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
           at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
           at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
           at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
           at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:93)
           at aspect.AspectTest.main(AspectTest.java:10)
Caused by: java.lang.IncompatibleClassChangeError: class net.sf.cglib.core.DebuggingClassWriter has interface org.objectweb.asm.ClassVisitor as super class
           at java.lang.ClassLoader.defineClass1(Native Method)
           at java.lang.ClassLoader.defineClass(Unknown Source)
           at java.security.SecureClassLoader.defineClass(Unknown Source)
           at java.net.URLClassLoader.defineClass(Unknown Source)
           at java.net.URLClassLoader.access$100(Unknown Source)
           at java.net.URLClassLoader$1.run(Unknown Source)
           at java.net.URLClassLoader$1.run(Unknown Source)
           at java.security.AccessController.doPrivileged(Native Method)
           at java.net.URLClassLoader.findClass(Unknown Source)
           at java.lang.ClassLoader.loadClass(Unknown Source)
           at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
           at java.lang.ClassLoader.loadClass(Unknown Source)
           at net.sf.cglib.core.DefaultGeneratorStrategy.getClassVisitor(DefaultGeneratorStrategy.java:30)
           at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:24)
           at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
           at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:144)
           at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:116)
           at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
           at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
           at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)
           at org.springframework.aop.framework.Cglib2AopProxy.createEnhancer(Cglib2AopProxy.java:228)
           at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:170)
           at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:476)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1426)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
           ... 11 more

This exception will be thrown,if we have the cglib.jar referring to a incompatible asm.jar set in our classpath.For instance if we have cglib-3.1.jar we will get this exception when we have asm-3.1.jar set in the classpath.Hence to resolve this we need to remove this older version of asm.jar and refer the asm.jar version greater than 4.0.So if we add the asm-4.0.jar(which is the compatible version for the cglib-3.1) to our classpath,we will not get the above exception.

java.lang.NoClassDefFoundError: org/objectweb/asm/Type

In this post we will see how to resolve the exception "java.lang.NoClassDefFoundError: org/objectweb/asm/Type".This exception may occur when working on spring AOP projects and the full exception stacktrace will look like below:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employee' defined in class path resource [aop.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/objectweb/asm/Type
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
           at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
           at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
           at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
           at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
           at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
           at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
           at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
           at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
           at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:93)
           at aspect.AspectTest.main(AspectTest.java:10)
Caused by: java.lang.NoClassDefFoundError: org/objectweb/asm/Type
           at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:184)
           at net.sf.cglib.core.KeyFactory.(KeyFactory.java:66)
           at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)
           at org.springframework.aop.framework.Cglib2AopProxy.createEnhancer(Cglib2AopProxy.java:228)
           at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:170)
           at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:476)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1426)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
           ... 11 more
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
           at java.net.URLClassLoader$1.run(Unknown Source)
           at java.net.URLClassLoader$1.run(Unknown Source)
           at java.security.AccessController.doPrivileged(Native Method)
           at java.net.URLClassLoader.findClass(Unknown Source)
           at java.lang.ClassLoader.loadClass(Unknown Source)
           at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
           at java.lang.ClassLoader.loadClass(Unknown Source)
           ... 23 more

This exception will be thrown if we don't have the asm.jar in the class path and make sure to add the same to your project classpath.You can download the asm.jar from the site here.

java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

When we try to implement the Spring AOP,we may get this exception -"org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor".
 
The full exception stacktrace will look like below:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:965)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:911)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
            at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
            at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
            at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
            at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
            at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:728)
            at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:449)
            at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
            at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:93)
            at aspect.AspectTest.main(AspectTest.java:10)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
            at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
            at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:958)
            ... 12 more
Caused by: java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
            at org.springframework.aop.framework.adapter.DefaultAdvisorAdapterRegistry.(DefaultAdvisorAdapterRegistry.java:49)
            at org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry.(GlobalAdvisorAdapterRegistry.java:31)
            at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.(AbstractAutoProxyCreator.java:118)
            at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.(AbstractAdvisorAutoProxyCreator.java:47)
            at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.(AspectJAwareAdvisorAutoProxyCreator.java:46)
            at org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator.(AnnotationAwareAspectJAutoProxyCreator.java:48)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
            at java.lang.reflect.Constructor.newInstance(Unknown Source)
            at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
            ... 14 more
Caused by: java.lang.ClassNotFoundException: org.aopalliance.intercept.MethodInterceptor
            at java.net.URLClassLoader$1.run(Unknown Source)
            at java.net.URLClassLoader$1.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(Unknown Source)
            at java.lang.ClassLoader.loadClass(Unknown Source)
            at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
            at java.lang.ClassLoader.loadClass(Unknown Source)
            ... 25 more

This exception will be thrown if we don't have the aopalliance.jar in the class path and make sure to add the same to your project classpath.You can download the aopalliance.jar from the spring  official site here.

Friday 20 March 2015

Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces

While we setting up the spring AOP project,sometimes we will get this exception -org.springframework.aop.framework.AopConfigExceptionCannot proxy target class because 
CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.
The full exception stacktrace will look like below:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employee' defined in class path resource [aop.xml]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
           at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
           at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
           at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
           at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
           at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
           at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
           at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
           at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
           at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:93)
           at aspect.AspectTest.main(AspectTest.java:10)
Caused by: org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.
           at org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(DefaultAopProxyFactory.java:67)
           at org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy(ProxyCreatorSupport.java:104)
           at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:476)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1426)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
           ... 11 more

This exception will be thrown if we don't have the cglib.jar in the class path and make sure to add the same in your project classpath.This jar can be download  from here.

Thursday 19 March 2015

Implementing logging using spring AOP

In this post we will see how to implement the logging using spring AOP. Logging is one of the cross cutting concerns which span across the multiple layer in the application.Using Spring AOP  we don't need to write the logging statements in each and every method of the class which needs to be logged.Instead we will define the cross cutting concern which is logging in our case in a single aspect(i.e Class) and we will make this aspect to execute in and around of the matched joint point(i.e method execution in spring AOP).

Below code example will give us an better idea on this.

Employee - Class for which we like to enable the logging.
LoggingAspect - Aspect class which contains and execute the advice on the employee bean.
aop.xml - Metadata information to the spring container.
AspectTest - Class which loads the spring container and gets the employee bean from the container                         and invokes the method on it.

Employee.java

package aspect;

public class Employee {

private String id=null;

private String name=null;

private double salary=0;

public String getId() {
return id;
}

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

public String getName() {
return name;
}

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

public double getSalary() {
return salary;
}

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

public Double getAnnualSalary()
{
return new Double(salary*12);
}
 
public Double decrementSalary()
{
String decValue=null;
return new Double(decValue);
}
}

LoggerAspect.java

package aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class LoggerAspect {

@Pointcut("execution(* aspect.*.*(..))")
public void selectall(){}

@Around("selectall()")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable
{
String className=joinPoint.getTarget().getClass().getName();
String methodName=joinPoint.getSignature().getName();
System.out.println("Start of the Method "+className+":"+methodName);
Object object=joinPoint.proceed();
System.out.println("End of the Method "+className+":"+methodName);
return object;
}

@AfterReturning(pointcut="selectall()",returning="retvalue")
public void AfterReturningAdvice(JoinPoint joinPoint,Object retvalue)
{
String className=joinPoint.getTarget().getClass().getName();
String methodName=joinPoint.getSignature().getName();
if(retvalue!=null)
System.out.println("Value returned from method "+className+":"+methodName+"
                is:"+retvalue);
}

@AfterThrowing(pointcut="selectall()",throwing="ex")
public void AfterThrowingAdvice(JoinPoint joinPoint,Exception ex)
{
String className=joinPoint.getTarget().getClass().getName();
String methodName=joinPoint.getSignature().getName();
System.out.println("Exception encountered in Method "+className+":"+methodName
+" and exception is:"+ex.toString());
}
}


Pointcut and JointPoints

@Pointcut - Pointcut will define the joint point i.e method execution for which the logging has to be enabled.This pattern(execution(* aspect.*.*(..))) will match any method execution  in the class of  aspect package which  contains zero or more arguments.

Types of advice- Aspect will execute the below advice on the target object i.e on employee bean.

@Around - This advice will be executed both before and after the method execution(which matches with the defined pointcut).
@AfterReturningAdvice - This advice will be executed after the method execution(which matches with the defined pointcut) is returned normally without any exception.
@AfterThrowing - This advice will be executed when the exception is returned from the method execution(which matches with the defined pointcut).

aop.xml

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

<aop:aspectj-autoproxy/>

<bean id ="employee" class="aspect.Employee">
<property name="id" value="E12"/>
<property name="name" value="Rahul"/>
<property name="salary" value="3120"/>
</bean>

<bean id="aspectannot" class="aspect.Aspect"/>

</beans>


AspectTest.java


package aspect;

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

public class AspectTest {

  public static void main(String[] args) {

  ApplicationContext context= new ClassPathXmlApplicationContext(new String[]{"aop.xml"});
  Employee emp= context.getBean("employee", Employee.class);
  double annualSalary=emp.getAnnualSalary();//1
  try
  {
  double decSalary=emp.decrementSalary(0);//2
  }
  catch(Exception e)
  {
 //ignore the exception
  }
  }

}


OUTPUT

Start of the Method aspect.Employee:getAnnualSalary
End of the Method aspect.Employee:getAnnualSalary
Value returned from method aspect.Employee:getAnnualSalary is:37440.0
Start of the Method aspect.Employee:decrementSalary
Exception encountered in Method aspect.Employee:decrementSalary and exception is:java.lang.NullPointerException

As we can see in the output,on each method execution of the employee bean corresponding advises was executed by the LoggerAspect.

Monday 9 March 2015

BeanCurrentlyInCreationException: Error creating bean with name : Requested bean is currently in creation: Is there an unresolvable circular reference?

In this post we will see how to resolve this exception-"BeanCurrentlyInCreationException: Error creating bean with name : Requested bean is currently in creation: Is there an unresolvable circular reference?" in spring.This exception is thrown in the below scenario:
  1. When there is an circular reference between the beans. For instance ClassA contains the instance member of type ClassB and class B too has ClassA as instance member. 
  2. And we use the constructor arguments to inject the dependencies between these beans.
Below code sample will explain this scenario.
  • ClassA,ClassB- bean classes for which there is an  circular dependencies between them.
  • CircularDemo -Main class which will load and initialize the spring container.
  • circontext.xml - metadata configuration details for the spring container.
ClassA.java

package test;

public class ClassA {

private ClassB classB=null;

public ClassB getClassB() {
return classB;
}

public void setClassB(ClassB classB) {
this.classB = classB;
}

@Override
public String toString() {
return "ClassA";
}

}

ClassB.java

package test;

public class ClassB {

private ClassA classA=null;

public ClassA getClassA() {
return classA;
}

public void setClassA(ClassA classA) {
this.classA = classA;
}

@Override
public String toString() {
return "ClassB";
}
}

circontext.xml

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

<bean id="classA" class="test.ClassA">
<constructor-arg ref="classB"/>
</bean>

<bean id="classB" class="test.ClassB">
<constructor-arg ref="classA"/>
</bean>

</beans>

As we can see in the application context file,we used the constructor arguments to inject the dependencies for bean ClassA and ClassB

CircularDemo.java

package test;

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

public class CircularDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext bf= new ClassPathXmlApplicationContext(new String[]
               {"circontext.xml"});
ClassA classA= bf.getBean("classA",ClassA.class);
   System.out.println("Bean Loaded:"+classA);
}
}

OUTPUT:

When we run the main program - CircularDemo,we will get the below exception

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'classA' defined in class path resource [circontext.xml]: Cannot resolve reference to bean 'classB' while setting constructor argument; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'classB' defined in class path resource [circontext.xml]: Cannot resolve reference to bean 'classA' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'classA': Requested bean is currently in creation: Is there an unresolvable circular reference?

To resolve this exception,declare the dependencies between the beans through the property setters instead of the constructor arguments as shown below.

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

<bean id="classA" class="test.ClassA">
<property name="classB" ref="classB"/>
</bean>

<bean id="classB" class="test.ClassB">
<property name="classA" ref="classA"/>
</bean>

</beans>

Now if we run the CircularDemo with the above application context file,we will get the expected output.

Bean Loaded:ClassA

Saturday 7 March 2015

No matching bean of type [] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency

In this post we will see how to resolve this exception-"NoSuchBeanDefinitionException:No matching bean of type [] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency" in spring.Click this  link to know about the autowire feature in spring and the various types.Coming back to our topic, this exception is thrown in the below scenario:
  1. When we  autowire the bean collaborators by constructor type,so that the spring container will resolve the bean dependencies automatically
  2. And there was  no bean declared or exist in the application context which is same as type of the constructor argument of the bean to be autowired.
Below code sample will explain this scenario.
  • Car- bean class for which the dependencies has to be resolved automatically by their constructor arguments type.
  • Engine - bean class which is set as the property of the Car object .
  • CarDemo -main class which will load the spring container and get the car bean from the container.
  • carcontext.xml - metadata configuration details for the spring container.
Car.java

package test;

public class Car {

private Engine engine=null;

public Car(Engine engine) {
super();
this.engine = engine;
}

public Engine getEngine() {
return engine;
}

@Override
public String toString() {
return "Car [engine=" + engine + "]";
}
}

Engine.java

package test;

public class Engine {

private int engineNumber;

private int engineCost;

public int getEngineNumber() {
return engineNumber;
}

public void setEngineNumber(int engineNumber) {
this.engineNumber = engineNumber;
}

public int getEngineCost() {
return engineCost;
}

public void setEngineCost(int engineCost) {
this.engineCost = engineCost;
}

@Override
public String toString() {
return "Engine [engineNumber=" + engineNumber + ", engineCost="
+ engineCost + "]";
}
}

carcontext.xml

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

<bean id="car" class="test.Car" autowire="constructor">
</bean>

</beans>

As we can see in the application context file,we used the attribute autowire="constructor" to make the container to automatically inject and resolve the dependencies for the car bean.Since the Car bean has the constructor of argument type test.Engine,container will look for the bean of type "test.Engine" and inject the same.

CarDemo.java

package test;

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

public class CarDemo {

public static void main(String[] args) {
ApplicationContext bf= new ClassPathXmlApplicationContext(new String[]{"carcontext.xml"});
Car car= bf.getBean("car",Car.class);
   System.out.println(car);
}

}


OUTPUT:

When we run the main program - CarDemo,we will get the below exception

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'car' defined in class path resource [carcontext.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [test.Engine]: : No matching bean of type [test.Engine] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [test.Engine] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray
(ConstructorResolver.java:730)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor
(ConstructorResolver.java:196)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance
(AbstractAutowireCapableBeanFactory.java:907)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean
(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject
(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton
(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean
(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons
(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization
(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh
(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at test.CarDemo.main(CarDemo.java:9)

While autowiring the dependencies for the car bean by constructor arguments, container could not found a bean of type test.Engine and hence this exception was thrown.

To resolve this,make sure we declare a bean of type test.Engine in the application context file so that the container will inject the same to Car bean by autowiring.

<bean id="engine" class="test.Engine">
<property name="engineNumber" value="2301"/>
<property name="engineCost" value="120000"/>
</bean>

Now if we run the CarDemo with the above change in the carcontext.xml,we will get the expected output

Car [engine=Engine [engineNumber=2301, engineCost=120000]]

Thursday 5 March 2015

No unique bean of type [] is defined: expected single matching bean but found 2

In this post we will see how to resolve the exception-"NoSuchBeanDefinitionException:No unique bean of type [] is defined: expected single matching bean but found 2" in spring.By using autowiring feature in spring,we can make the spring container to resolve the bean dependencies automatically and hence we don't need to declare the dependencies either through constructor arguments or through properties in the application context file.We can autowire the beans by:
  • ByName  - spring container will autowire the dependencies by looking up the bean name in the application context file which will match with the bean property name.Lets says  a bean X has the property y(has the setY method too) and the  spring container will look for the bean named "y" in the application context and inject the same to bean X.
  • ByType   - spring container will autowire the property with the bean which has the same type.If more than one bean exists in the container of the same type,then the above fatal exception is thrown
  • Constructor - Its as same as ByType,but it applies to the argument type of the bean to be autowired.If more than one bean or no bean exist in the container of the same constructor type then the above fatal exception is thrown.
Let say we have the below classes and we would like to autowire the  dependencies by type.
  • Bus - Bean class for which the container has to autowire the dependencies by type.
  • Engine - Bean class which is set as the property of the bus object.
  • BusDemo -Main class which will load the spring container and get the bus bean from the container.
  • buscontext.xml - metadata configuration details for the spring container.
Bus.java

package test;

public class Bus {
private Engine engine=null;

public Engine getEngine() {
return engine;
}

public void setEngine(Engine engine) {
this.engine = engine;
}

        @Override
public String toString() {
return "Bus [engine=" + engine + "]";
}
}
   

Engine.java

package test;

public class Engine {
private String engineMake;
private String engineCost;

public String getEngineMake() {
return engineMake;
}

public void setEngineMake(String engineMake) {
this.engineMake = engineMake;
}

public String getEngineCost() {
return engineCost;
}

public void setEngineCost(String engineCost) {
this.engineCost = engineCost;
}
       
        @Override
public String toString() {
return "Engine [engineMake=" + engineMake + ", engineCost="
+ engineCost + "]";
}

buscontext.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:aop="http://www.springframework.org/schema/aop" 
xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="bus" class="test.Bus" autowire="byType">
</bean>

<bean id="primaryengine" class="test.Engine">
<property  name="engineMake" value="Ford"/>
<property  name="engineCost" value="100000"/>
</bean>

<bean id="secondaryengine" class="test.Engine">
<property  name="engineMake" value="Renault"/>
<property  name="engineCost" value="50000"/>
</bean>

</beans>

As we can see in the application context file,we use the attribute autowire="byType" to make the container to automatically inject and resolve the dependencies for the bus bean.Container will look for the bean of type "test.Engine" and inject the same to the engine property of the bus bean.

BusDemo.java

package test;

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

public class BusDemo {
public static void main(String[] args) {
ApplicationContext bf= new ClassPathXmlApplicationContext(new String[]  
               {"buscontext.xml"});
Bus bus= bf.getBean("bus",Bus.class);
       System.out.println(bus);
}

}

OUTPUT:

When we run the main program - BusDemo,we will get the below exception

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bus' defined in class path resource [buscontext.xml]: Unsatisfied dependency expressed through bean property 'engine': : No unique bean of type [test.Engine] is defined: expected single matching bean but found 2: [primaryengine, secondaryengine]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [test.Engine] is defined: expected single matching bean but found 2: [primaryengine, secondaryengine]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType
(AbstractAutowireCapableBeanFactory.java:1167)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean
(AbstractAutowireCapableBeanFactory.java:1059)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean
(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean
(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject
(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton
(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean
(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean
(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons
(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization
(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh
(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at test.BusDemo.main(BusDemo.java:9)

While autowiring the dependencies for the bus bean, container found two beans of type  test.Engine instead of one and hence this exception was thrown

We can resolve this exception either in two ways.Let say we want the container to autowire the dependency for the bus bean with the primaryengine bean.

1)Set the primary attribute of the primaryengine bean to true,so that the container will nominate this bean to inject it to the bus bean by autowiring

   <bean id="primaryengine" class="test.Engine" primary="true">
   <property  name="engineMake" value="Ford"/>
   <property  name="engineCost" value="100000"/>
   </bean>

or

2)Set the autowire-candidate attribute of the secondaryengine bean to false,so that the container will exclude this bean for autowiring  and hence inject the primaryengine bean to the bus bean. 

<bean id="secondaryengine" class="test.Engine" autowire-candidate="false">
<property  name="engineMake" value="Renault"/>
<property  name="engineCost" value="50000"/>
</bean>

Now if we run the BusDemo with the change(either option 1 or 2 as above) in the buscontext.xml,we get the below output

Bus [engine=Engine [engineMake=Ford, engineCost=100000]]