为什么Spring要支持Autowire(自动装配)
先写几个类,软件开发,首先界说一个Animal接口暗示动物:
public interface Animal {
public void eat();
}
写一个Animal接口的实现Tiger类:
public class Tiger implements Animal {
@Override
public void eat() {
System.out.println("Tiger.eat()");
}
@Override
public String toString() {
return "I'm a tiger";
}
}
写一个动物园类Zoo,持有Animal接口,暗示动物园中有动物:
public class Zoo {
private Animal animal;
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
@Override
public String toString() {
if (animal == null) {
return null;
}
return animal.toString();
}
}
设置一下spring文件,由于这个成果研究的是Autowire,因此我定名为autowire.xml:
<?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-3.0.xsd">
<bean id="tiger" class="org.xrq.action.by.Tiger" />
<bean id="zoo" class="org.xrq.action.by.Zoo">
<property name="animal" ref="tiger" />
</bean>
</beans>
Spring引入Autowire(自动装配)机制就是为了办理<bean>标签下<property>标签过多的问题,<property>标签过多会激发两个问题:
因此,为了办理利用<property>标签注入工具过多的问题,Spring引入自动装配机制,简化开拓者设置难度,低落xml文件设置巨细。
利用Autowire去除<property>标签
下面来看一下利用Autowire去除<property>,autowire有两处点:
凡是都是在<beans>根标签下设置自动装配较量多,default-autowire有四种取值:
这里研究的是去除<property>标签,因此第一种不管;constructor装配不太常用,因此这里也不管,重点看最常用的byName与byType,至于详细利用哪种按照本身的业务特点举办相应的配置。
首先看一下byName,byName意为在spring设置文件中查询beanName与属性名一致的bean并举办装配,若范例不匹配则报错,autowire.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
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-autowire="byName">
<bean id="animal" class="org.xrq.action.by.Tiger" />
<bean id="zoo" class="org.xrq.action.by.Zoo" />
</beans>
看到Zoo中有一个名为animal的属性,我将Tiger这个bean也定名为animal,由于Tiger是Animal接口的实现类,因此Spring可以找到beanName为animal的bean并自动装配到Zoo的animal属性中,这就是byName的自动装配形式。
接着看一下byType的自动装配形式,byType意为在spring设置文件中查询与属性范例一致的bean并举办装配,若有多个沟通范例则报错(下一部门讲),autowire.xml假如利用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
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-autowire="byType">
<bean id="tiger" class="org.xrq.action.by.Tiger" />
<bean id="zoo" class="org.xrq.action.by.Zoo" />
</beans>