Ad

Monday, 23 March 2015

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]]