package com.jing.pojo; public class Cat { public void shout(){ System.out.println("喵"); } }
package com.jing.pojo; public class Dog { public void shout(){ System.out.println("汪"); } }
public class Person { private Cat cat; private Dog dog; private String name; public Cat getCat() { return cat; } public void setCat(Cat cat) { this.cat = cat; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "cat=" + cat + ", dog=" + dog + ", name='" + name + '\'' + '}'; } }
所谓“装配”,是为bean注入依赖(引用型属性)。Spring中有三种装配(依赖注入)方式:
<?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.jing.pojo.Cat"/> <bean id="dog" class="com.jing.pojo.Dog"/> <bean id="person" class="com.jing.pojo.Person"> <property name="name" value="YuJing"/> <!--依赖注入--> <property name="cat" ref="cat"/> <property name="dog" ref="dog"/> </bean> </beans>
<?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="dog" class="com.jing.pojo.Dog"></bean> <bean id="cat" class="com.jing.pojo.Cat"></bean> <!--byType:会自动在容器上下文查找,和自己对象属性类型相同的bean!--> <bean id="person" class="com.jing.pojo.Person" autowire="byType"></bean> </beans>
<?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="dog" class="com.jing.pojo.Dog"></bean> <bean id="cat" class="com.jing.pojo.Cat"></bean> <!--byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid!--> <bean id="person" class="com.jing.pojo.Person" autowire="byName"></bean> </beans>