Spring auto-wiring mode constructor
Auto-wiring by constructor is similar to byType, but it applies to constructor arguments. If there isn't exactly one
bean of the constructor argument type in the container, a fatal error is raised.
package com.java2novice.beans;
public class PaymentGateway {
private Order order;
public PaymentGateway(Order ord){
this.order = ord;
}
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 based configuration file shows injecting dependencies using constructor-arg property.
<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">
<constructor-arg>
<ref bean="orderBean" />
</constructor-arg>
</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 with auto-wire configuration using constructor mode:
<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="constructor" />
<bean id="orderBean" 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());
}
}
|
|