Autowire-ByName
>>
It performs setter injection
>>
For this, all target class property names and dependent class bean ids must match.
>>
There is no possibility of getting ambiguity problem.
>>
It use 0-param constructor to create the object..
package com.nt.beans;
public class TravelAgent {
private TourPlan tp;
public TravelAgent() {
System.out.println("TravelAgent::0-param constructor");
}
public void setTp(TourPlan tp) {
System.out.println("TravelAgent.setTp()");
this.tp = tp;
}
@Override
public String toString() {
return "TravelAgent [tp=" + tp + "]";
}
}
package com.nt.beans;
import java.util.Arrays;
public class TourPlan {
private String places[];
public void setPlaces(String[] places) {
this.places = places;
}
@Override
public String toString() {
return "TourPlan [places=" + Arrays.toString(places) + "]";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="tp" class="com.nt.beans.TourPlan">
<property name="places">
<array>
<value>Simla</value>
<value>Goa</value>
<value>Delhi</value>
</array>
</property>
</bean>
<bean id="ta" class="com.nt.beans.TravelAgent" autowire="byName"/>
</beans>
package com.nt.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.nt.beans.TravelAgent;
public class AutowireByNameTest {
public static void main(String[] args) {
ApplicationContext ctx=null;
TravelAgent ta=null;
ctx=new ClassPathXmlApplicationContext("com/nt/cfgs/applicationContext.xml");
ta=ctx.getBean("ta",TravelAgent.class);
System.out.println(ta);
((AbstractApplicationContext) ctx).close();
}
}
Post a Comment