目录
一.byName
二.byType
快捷书写
people1
package org.example;
public class People1 {
public void eat(){
System.out.println("吃饭");
}
}
people2
package org.example;
public class People2 {
public void sleep(){
System.out.println("睡觉");
}
}
person
package org.example;
public class Person {
private People1 people1;
private People2 people2;
public People1 getPeople1() {
return people1;
}
public void setPeople1(People1 people1) {
this.people1 = people1;
}
public People2 getPeople2() {
return people2;
}
public void setPeople2(People2 people2) {
this.people2 = people2;
}
@Override
public String toString() {
return "person{" +
"people1=" + people1 +
", people2=" + people2 +
'}';
}
}
一.byName
自动在容器上下文查找与set方法后面的值对应的bean id
(理解:
例如针对people1来讲
将People1这个字符串的首字母小写得到people1
然后去spring的容器里查找与people1相同beanid
如果找不到则报空指针异常(也就是名称要保证全局唯一)
<?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="people1" class="org.example.People1"/>
<bean id="people2" class="org.example.People2 "/>
<bean id="person" class="org.example.Person" autowire="byName">
</bean>
</beans>
测试
package org.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test8 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person person= context.getBean("person",Person.class);
person.getPeople1().eat();
person.getPeople2().sleep();
}
}
二.byType
自动在容器上下文查找与自己对象属性相同的bean
使用byType仍然可以得到如上测试的结果
但是要保证自己对象的属性类型要全局唯一
使用byType可以省略id的书写
<bean class="org.example.People1"/>
<bean class="org.example.People2 "/>
<bean id="person" class="org.example.Person" autowire="byType">
快捷书写
new ClassPathXmlApplicationContext
点回车