我们知道想要把一个bean对象注入到一个属性上,可以用ref的方式来引用bean的id,但是这样子做会容易使得xml杂乱,如果ref引用过多,我们需要定义很多个bean,需要起很多个id名。本章介绍的内部bean可以解决这样的问题,内部bean是匿名的,而且直接出现在需要它的地方,这样一来我们不必为命名而操心,整个xml结构也清晰了起来。
inner_bean.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.xsd">
<bean id="master" class="upc.yqs.Master">
<property name="age" value="10"></property>
<property name="pets">
<list>
<bean class="upc.yqs.Pet">
<property name="name" value="猫"></property>
</bean>
<bean class="upc.yqs.Pet">
<property name="name" value="狗"></property>
</bean>
</list>
</property>
</bean>
</beans>
Master类:
import java.util.List;
public class Master
{
public int age;
List<Pet> pets;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Pet> getPets() {
return pets;
}
public void setPets(List<Pet> pets) {
this.pets = pets;
}
}
Pet类:
public class Pet
{
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sound()
{
System.out.println(name+"叫了一下");
}
}
测试类:
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import upc.yqs.Master;
import upc.yqs.Pet;
import java.util.Iterator;
public class InnerBeanTest
{
public ApplicationContext context;
@Before
public void getContext()
{
context= new ClassPathXmlApplicationContext("inner_bean.xml");
}
@Test
public void innerBeanTest()
{
Master master=(Master) context.getBean("master");
Iterator<Pet> it=master.getPets().iterator();
while (it.hasNext())
{
it.next().sound();
}
}
}
输出:
猫叫了一下
狗叫了一下