Constructor argument type matching in Spring
April 08, 2013
In spring when we can initialize bean as constructor argument, the dependency can be passed with help of type also. If constructor arguments are int and String or any custom object, we need to give fully qualified name to the attribute type in declaring bean in application XML. Primitive data type can be directly written.
spring-config.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <bean id="ent" class="com.concretepage.Entitlement"> <constructor-arg type="java.lang.String" value="Entitlement"/> <constructor-arg type="int" value="100"/> </bean> </beans>
package com.concretepage; public class Entitlement { private String name; private int time; public Entitlement(String name,int time){ this.name=name; this.time=time; } public String getName() { return name; } public int getTime() { return time; } }
package com.concretepage; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringDemo { public static void main(String... args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); Entitlement ent=(Entitlement)context.getBean("ent"); System.out.println(ent.getName()); System.out.println(ent.getTime()); } }