Spring - Inner Beans
There are times when your class has a reference to an instance of some other class. Say a 'Car' class holds a reference of a 'Wheel' class. And you do not want anyone else to use the 'Wheel' bean created by spring.
In such cases we don't ask Spring to create a separate bean for 'Wheel' . But tell Spring to create a 'Wheel' bean only for 'Car' class. In such cases the 'Wheel' bean is said to be Inner Bean.
Let us see with the below example :
Car Class
class Car {
Wheel wheel;
public Wheel getWheel() {
return wheel;
}
public void setWheel(Wheel wheel) {
this.wheel = wheel;
}
}
Wheel Class
class Wheel {
String tyreType;
public String getTyreType() {
return tyreType;
}
public void setTyreType(String tyreType) {
this.tyreType = tyreType;
}
}
Now, since the 'Car' class has a reference to an instance of 'Wheel' class. We will define them in 'application-context.xml'.
application-context.xml
<?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-3.0.xsd">
<bean name = "car" class = "Car">
<property name = "wheel"/>
<bean class = "Wheel">
<property name = "wheel" value="Thick Tire"/>
</bean>
</property>
</bean>
</beans >
Since, the 'Car' class has a reference to an instance of 'Wheel' class
class Car {
Wheel wheel;
...
...
}
We have created the equivalent of it :
<bean name = "car" class = "Car">
<property name = "wheel"/>
...
Now, in the next line we haven't created the 'Wheel' bean separately. But created it inside the 'wheel' property of 'Car' class :
<bean name = "car" class = "Car">
<property name = "wheel"/>
<bean class = "Wheel">
<property name = "wheel" value="Thick Tire"/>
</bean>
</property>
</bean>
And thus we create an inner bean 'Wheel', which could only be used by the 'Car' bean.
Finally, in the main() method we define our application code to interact with spring.
import org.springframework.context.ApplicationContext;
public class FirstSpringApp {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
Car car = (Car)applicationContext.getBean("car");
System.out.println("The Car tire type is : "+car.getWheel().getTireType());
}
}
Just note, we have just asked spring to give us a 'Car' object.
Car car = (Car)applicationContext.getBean("car");
And in the background, spring has created the 'Wheel' object and injected into the 'Wheel' reference of 'Car' class.
Output :
The Car tire type is : Thick Tire