自动装配
<beanid="foo" class="...Foo" autowire="autowire type">
有四种自动装配类型:
1.byName:寻找和属性名相同的bean,若找不到,则装不上。
2.byType:寻找和属性类型相同的bean,找不到,装不上,找到多个抛异常。
3.constructor:查找和bean的构造参数一致的一个或多个bean,若找不到或找到多个,抛异常。按照参数的类型装配
4.autodetect:(3)和(2)之间选一个方式。不确定性的处理与(3)和(2)一致。
5.defualt:这个需要在<beansdefualt-autorwire=“指定”/>
说明:不推荐使用,但是作为授课,我们还是要了解这些知识,面试用的上.
6.no:不自动装配,这是autowrite的默认值.
(1) byName的用法:
package com.hsp.autowire;
public class Master {
private String name;
private 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 com.hsp.autowire;
import javax.annotation.Resource;
public class Dog {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 配置一个master对象 -->
<bean id="master" class="com.hsp.autowire.Master" autowire="byName">
<property name="name">
<value>顺平</value>
</property>
</bean>
<!-- 配置dog对象 -->
<bean id="dog" class="com.hsp.autowire.Dog">
<property name="name" value="小黄" />
<property name="age" value="3" />
</bean>
</beans>
package com.hsp.autowire;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/autowire/beans.xml");
//获取
Master master=(Master) ac.getBean("master");
System.out.println(master.getName()+" 养 "+master.getDog().getName());
}
}
顺平 养 小黄
(2) byType: byType寻找和属性类型相同的bean,找不到,装不上,找到多个抛异常。
(3) constructor: autowire="constructor"
说明:查找和bean的构造参数一致的一个或 多个bean,若找不到或找到多个,抛异常。按照参数的类型装配
(4) autodetect 说明:autowire="autodetect"(3)和(2)之间选一个方式。不确定性的处理与(3)和(2)一致。
(5) defualt 这个需要在<beansdefualt-autorwire=“指定” />
当你在<beans>指定了default-atuowrite后, 所有的bean的 默认的autowire就是 指定的装配方法;
如果没有在<beansdefualt-autorwire=“指定” /> 没有 defualt-autorwire=“指定” ,则默认是defualt-autorwire=”no”
(6) no:不自动装配