属性autowire值byName
byName:会自动在容器上下文中查找和自己实体类对象中set方法后面的值对应的bean的id
测试:
实体类People
public class People {
private Cat cat;
private Dog dog;
private String name;
public Cat getCat() {
return cat;
}
public Dog getDog() {
return dog;
}
public String getName() {
return name;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
}
Cat类:
public class Cat {
public void shout(){
System.out.println("miao~");
}
}
Dog类:
public class Dog {
public void shout(){
System.out.println("wang~");
}
}
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">
<!-- 注册cat和dog对象交给spring来管理-->
<bean id="cat" class="pojo.Cat"/>
<bean id="dog" class="pojo.Dog"/>
<!-- 使用属性autowire中的byName值通过spring容器中上下文注入cat和dog中的对象-->
<bean id="people" class="pojo.People" autowire="byName">
<property name="name" value="chenhui"/>
</bean>
</beans>
测试类:
@org.junit.Test
public void test(){
//通过ClassPathXmlApplicationContext对象加载配置文件方式将javabean对象交给spring来管理
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
// user已经创建好了 , 通过无参构造
People people = applicationContext.getBean("people", People.class);
people.getCat().shout();
people.getDog().shout();
System.out.println(people.getName());
}
结果:
属性autowire值byType
byType:会自动在容器上下文中查找和自己实体类对象中类型相同的bean,此时与bean的id无关了,因此bean的id可以省略,如果spring容器中有两个类型相同的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">
<!-- 注册cat和dog对象交给spring来管理-->
<bean class="pojo.Cat"/>
<bean class="pojo.Dog"/>
<!-- 使用属性autowire中的byType值通过spring容器中上下文注入cat和dog中类型的对象-->
<bean id="people" class="pojo.People" autowire="byType">
<property name="name" value="chenhui"/>
</bean>
</beans>
结果:
总结:
- 使用autowire属性时必须有对应的set方法
- 使用byName值时,需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
- 使用byType值时,需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致