前言
自动装配是Spring满足Bean依赖的一种方式。
Spring中的三种装配方式
- 在xml中显示配置
- 在java中显示配置
- 隐式的自动装配bean
直接上demo:(XML自动装配)
猫类:
public class Cat {
public void shout(){
System.out.println("猫叫");
}
}
狗类:
public class Dog {
public void shout(){
System.out.println("狗叫");
}
}
人类:(一个人有一只猫和一只狗)
public class People {
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 "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
beans.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="cat" class="cn.Cat"></bean>
<bean id="dog" class="cn.Dog"></bean>
<!--注意这里,自动装配前 和 自动装配后的区别-->
<bean id="people" class="cn.People" autowire="byName">
<property name="name" value="詹大先生"></property>
<property name="cat" ref="cat"></property>
<property name="dog" ref="dog"></property>
</bean>
</beans>
测试类:
public class MyTest {
//主类 可以通过 psvm打出来 不用一个个代码去敲
public static void main(String[] args) {
//获取Spring 的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people=context.getBean("people", People.class);
people.getCat().shout();
people.getDog().shout();
}
}
测试结果:
自动装配后的beans,xml:(注意!beans.xml 自动装配前 和 自动装配后的区别)
1. ByName自动装配
byname:需要保证所有的bean的id唯一,并且这个bean要和自动注入的属性的set方法的值一致。
<?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="cn.Cat"></bean>
<bean id="dog" class="cn.Dog"></bean>
<!--byname:会自动在容器上下文中查找,和自己对象set方法后面值对应的bean id -->
<!--这边举例的是byname-->
<bean id="people" class="cn.People" autowire="byName">
<property name="name" value="詹大先生"></property>
</bean>
</beans>
测试结果:
2. ByType自动装配
bytype:需要保证所有的bean的class唯一,并且这个bean要和自动注入的属性的类型一致。
<?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="cn.Cat"></bean>
<bean id="dog" class="cn.Dog"></bean>
<!--bytype:会自动在容器上下文中查找,和自己对象属性类型相同的bean -->
<bean id="people" class="cn.People" autowire="byType">
<property name="name" value="詹大先生"></property>
</bean>
</beans>
测试结果:
看完如果对你有帮助,点赞支持!