Spring auto-wiring mode byName
In spring, auto-wiring by name means autowiring by property name. This option will inspect the container and look for a bean
named exactly the same as the property which needs to be autowired. For example, if you have a bean definition which is set to autowire
by name, and it contains a master property (that is, it has a setMaster(..) method), Spring will look for a bean definition named master,
and use it to set the property.
This page gives an example how to auto-wire by name:
package com.java2novice.beans;
public class PaymentGateway {
private Order order;
public void setOrder(Order ord){
this.order = ord;
}
public Order getOrder() {
return order;
}
@Override
public String toString(){
return "ordering "+this.order.getItem()+" | price: "+this.order.getPrice();
}
}
|
package com.java2novice.beans;
public class Order {
private String item;
private String price;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
|
Here is the xml configuration file, which gives the normal way of injecting bean properties:
<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-3.0.xsd">
<bean id="paymentGateway" class="com.java2novice.beans.PaymentGateway" >
<property name="order" ref="orderBean" />
</bean>
<bean id="orderBean" class="com.java2novice.beans.Order" >
<property name="item" value="Java Book" />
<property name="price" value="RS 225" />
</bean>
</beans>
|
Here is the xml based configuration file, which shows how to auto-wire by name. Use autowire property to specify inject
by name:
<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-3.0.xsd">
<bean id="paymentGateway" class="com.java2novice.beans.PaymentGateway"
autowire="byName" />
<bean id="order" class="com.java2novice.beans.Order" >
<property name="item" value="Java Book" />
<property name="price" value="RS 225" />
</bean>
</beans>
|
Spring bean demo class:
package com.java2novice.test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.beans.PaymentGateway;
public class SpringDemo {
public static void main(String a[]){
String confFile = "applicationContext.xml";
ConfigurableApplicationContext context
= new ClassPathXmlApplicationContext(confFile);
PaymentGateway paymentGateway = (PaymentGateway) context.getBean("paymentGateway");
System.out.println(paymentGateway.toString());
}
}
|
|