自动装配Bean
环境搭建
public class person {
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 "person{" +
"dog=" + dog +
", cat=" + cat +
", name='" + name + '\'' +
'}';
}
}
显式装配
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="cat" class="com.Google.pojo.Cat"/>
<bean id="dog" class="com.Google.pojo.Dog"/>
<bean id="person" class="com.Google.pojo.person">
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
<property name="name" value="Spring"/>
</bean>
</beans>
这里person类的属性,都有对应的值。全都显式的配置好了
ByName自动装配
ByName:在Spring上下文中,person类的set方法后面的属性要与Bean id相同,才能自动装配
<bean id="cat" class="com.Google.pojo.Cat"/>
<bean id="dog" class="com.Google.pojo.Dog"/>
<!--ByName:在Spring上下文中,person类的set方法后面的属性要与Bean id相同,才能自动装配-->
<bean id="person" class="com.Google.pojo.person" autowire="byName">
<property name="name" value="Spring"/>
</bean>
ByType自动装配
ByType:在Spring上下文中,person类的属性的类型与Bean class一致,才能实现自动装配。适用于全局类型唯一的环境
<bean id="cat" class="com.Google.pojo.Cat"/>
<bean id="dog" class="com.Google.pojo.Dog"/>
<!--ByType:在Spring上下文中,person类的属性的类型与Bean class一致,才能实现自动装配-->
<bean id="person" class="com.Google.pojo.person" autowire="byType">
<property name="name" value="Spring"/>
</bean>