bean的自动装配
什么是bean的自动装配?
假如一个类要调用另一个类,那么我们之前的方法是把被调用的类在<property />中调用它。如图:
有了自动装配就不用麻烦了,接下来介绍自动装配bean。
首先自动装配bean需要<bean>中调用autowire如同<bean id="xx" class="xx" autowrie=" ">
autowire中有6个属性分别是byName, byType,constructor,autodetect,defualt,no这六个属性
接下来配合代码一一讲解
先看两个类文件
调用的类文件
package it.autowire;
public class Person {
private String name;
private Dog dog;//这个变量的类型是被调用类
public Person() {
}
//当xml文件中autowire的参数是constructor时,则会调用搞糟函数中类型与被调用bean类型匹配的bean
public Person(Dog dog) {
System.out.println("通过构造器配置");
this.dog=dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
被调用的类文件:
package it.autowire;
public class Dog {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Test类:
package it.autowire;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import it.bean.assemble.AllKindsService;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
ApplicationContext ac=new ClassPathXmlApplicationContext("it/autowire/beans.xml");
Person per=(Person) ac.getBean("person");
System.out.println(per.getName()+"的狗是"+per.getDog().getName());//使用红体方法时,需要调用dog对象
}}
byName:
会查找在调用类中调用的被调用类的类型的变量相同的对象名,并实现匹配,并完成装配(在person类中Dog对象的变量dog就和xml文件中id="dog"相匹配并调用
xml文件
byType:
寻找和属性类型相同的bean,找不到,装不上,找到多个抛异常。变量dog的类型是Dog,所以和在xml文件类型是Dog的dog相匹配完成注入
constructor:
查找和bean的构造参数一致的一个或 多个bean,若找不到或找到多个,抛异常。按照参数的类型装配
这个类型在类文件中会有点变化
public Person(Dog dog) {
System.out.println("通过构造器配置");
this.dog=dog;
}//需要这样一个构造函数,他的参数被调用的类型,且完成赋值
autodetect:
当autowire是autodetect时则会现根据construct装配,不行则通过ByType装配
default:
default这个需要在<beans defualt-autorwire=“指定”,指定后,autowire的值默认就是defaulit——autowire中指定的值
no:
不装配