自动装配Bean
大约 2 分钟Spring全家桶Spring入门
自动装配是Spring满足bean依赖的一种方式!Spring会在上下文中自动寻找,并自动给bean装配属性!
在Spring中有三种装配的方式:
1、在xml中显示的配置
<bean id="xxx" class="xxx">
<property name="xxx" value="xxx"/>
</bean>
2、在Java中显示配置
3、隐式自动装配bean
环境准备:
Cat.java
package com.kuang.pojo;
/**
* @author Administrator
*/
public class Cat {
public void shout(){
System.out.println("miao~");
}
}
Dog.java
package com.kuang.pojo;
/**
* @author Administrator
*/
public class Dog {
public void shout(){
System.out.println("wang~");
}
}
People.java
package com.kuang.pojo;
/**
* @author Administrator
*/
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;
}
}
测试类
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
people.getCat().shout();
people.getDog().shout();
}
Cat和Dog类自动装配,name属性在xml中显示的配置!
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="dog" class="com.kuang.pojo.Dog"/>
<!--
byName原理:会自动在容器上下文查找,和自己对象set方法后面的值对应的beanid
-->
<bean id="people" class="com.kuang.pojo.People" autowire="byName">
<property name="name" value="张三"/>
</bean>
</beans>
ByType自动装配
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="dog" class="com.kuang.pojo.Dog"/>
<!--
byType原理:会自动在容器上下文查找,和自己对象属性类型相同的bean
-->
<bean id="people" class="com.kuang.pojo.People" autowire="byType">
<property name="name" value="张三"/>
</bean>
</beans>
总结
- byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
- byType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!