How to inject inner bean in spring?
Inner beans are the beans that are defined within the scope of another bean. Thus, a <bean/> element inside the
<property/> or <constructor-arg/> elements is called inner bean. This page gives an example to inject inner bean in spring.
This example uses constructor based injection, the approach is similar for setter based injection.
Here is a class called PaymentGateway, which requires Order object to be injected.
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 void processOrder(){
System.out.println("Processing order: "+order.getItem());
}
}
|
Order class:
package com.java2novice.beans;
public class Order {
private String item;
private String price;
private String address;
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;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
|
Here is the xml based inner bean injection, note that when you are using inner bean configuration, bean id is not
required. The approach is same for setter based injection.
<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="paymentGwBean" class="com.java2novice.beans.PaymentGateway">
<constructor-arg>
<bean class="com.java2novice.beans.Order">
<property name="item" value="Java2Novice" />
<property name="price" value="RS 22.50" />
<property name="address" value="Bangalore" />
</bean>
</constructor-arg>
</bean>
</beans>
|
Finally SpringDemo class:
package com.java2novice.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.beans.PaymentGateway;
public class SpringDemo {
public static void main(String a[]){
String confFile = "applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(confFile);
PaymentGateway gateway = (PaymentGateway) context.getBean("paymentGwBean");
gateway.processOrder();
}
}
|
|