Wednesday, 15 May 2013

java - Why Spring throws exceptions when No default constructor is found -



java - Why Spring throws exceptions when No default constructor is found -

a simple test shopping application have 2 classes clothing , offers. on calling formalshirt bean, throws next exception

caused by: org.springframework.beans.factory.beancreationexception: error creating bean name 'diwalioffer' defined in class path resource [spring.xml]: instantiation of bean failed; nested exception org.springframework.beans.beaninstantiationexception: not instantiate bean class [offers]: no default constructor found; nested exception java.lang.nosuchmethodexception: offers.<init>()

now if comment offers constructor, app runs successfully. query why spring looks default constructor when there constructor?

clothing class

public class clothing { private int price; private list<offers> offer; public void setoffer(list<offers> offer) { this.offer = offer; } public void setprice(int price) { this.price = price; } }

.

offers class

public class offers { private int discount; private string promocode; public offers(int val1, string val2) { this.discount=val1; this.promocode=val2; } //public offers(){} /*default constructor added due spring exception in below */ /* caused by: org.springframework.beans.beaninstantiationexception: not instantiate bean class no default constructor found */ /* caused by: java.lang.nosuchmethodexception: com.test.shopping.offers.<init>() */ public void setdiscount(int discount) { this.discount = discount; } public void setpromocode(string promocode) { this.promocode = promocode; } }

spring.xml

<bean id="formalshirt" class="com.test.shopping.clothing"> <property name="price" value="800"></property> <property name="offer"> <list> <ref bean="diwalioffer" /> </list> </property> </bean> <bean id="diwalioffer" class="com.test.shopping.offers"> <property name="discount" value="10"></property> <property name="promocode" value="diwali"></property> </bean>

you need alter spring xml configuration of offers to:

<bean id="diwalioffer" class="com.test.shopping.offers"> <constructor-arg value="10"></constructor-arg> <constructor-arg value="diwali"></constructor-arg> </bean>

the way have configured it, spring first attempts phone call default constructor , phone call setters. of course of study there no default constructor, , there fore spring reports exception.

another alternative if using spring 3+ utilize java config, instead of xml config. have

@configuration public class appconfig { //add other beans @bean public offers diwalioffer() { homecoming new offers(10, diwali); } }

in case java config has benefit configuration not compile if didn't phone call constructor, ie. fail instead of fail late xml configuration

spring extremely flexible how creates beans, need declare how done

java spring

No comments:

Post a Comment