1.类
cat
public class Cat {
public void shout(){
System.out.println("喵喵~");
}
}
dog
public class Dog {
public void shout(){
System.out.println("汪汪~");
}
}
People
public class People {
private Dog dog;
private Cat cat;
private String name;
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"dog=" + dog +
", cat=" + cat +
", name='" + name + '\'' +
'}';
}
}
2.bean
ByName
<?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="cat" class="com.zy.pojo.Cat"></bean>
<bean id="dog" class="com.zy.pojo.Dog"></bean>
<bean id="people" class="com.zy.pojo.People" autowire="byName" >
<property name="name" value="狂神"></property>
<property name="cat" ref="cat"></property>
<property name="dog" ref="dog"></property>
</bean>
</beans>
ByType
<bean class="com.zy.pojo.Cat"></bean>
<bean class="com.zy.pojo.Dog"></bean>
<bean id="people" class="com.zy.pojo.People" autowire="byType">
<property name="name" value="小狂神"></property>
</bean>
3.测试
public class PeopleTest {
@Test
public void testPeople(){
ApplicationContext context = new ClassPathXmlApplicationContext("Peoplebeans.xml");
People people = context.getBean("people", People.class);
people.getCat().shout();
people.getDog().shout();
}
}