使用autowire标签完成bean的自动注入
首先,我们有如下两个类:
public class Student{
private String name;
private Book book;
//set and get methods
}
class Book{
private int ID;
//set and get methods
}
autowire=“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.xsd">
<!--配置业务层的对象-->
<!--通过指定autowire的方式,我们不需要再去为book指明对象信息,但是额外的bean的ID要与类中的变量名称相同,此处为book-->
<bean id="student" class="com.erwin.entity.Student" autowire="byName">
<property name="name" value="Erwin"></property>
</bean>
<!--student会自动找到下面这个bean对象,因为它的ID与Student类中相关变量的名称相同-->
<bean id="book" class="com.erwin.entity.Book">
<property name="ID" value="001"></property>
</bean>
</beans>
autowire=“byType”, 根据变量的类型自动注入
使用这种方式,必须保证当前xml中有且只有一个对应类的bean存在
<?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">
<!--配置业务层的对象-->
<!--通过指定autowire的方式,我们不需要再去为book指明对象信息,但是额外的bean的类型要在当前xml中存在,此处为Book类-->
<bean id="student" class="com.erwin.entity.Student" autowire="byName">
<property name="name" value="Erwin"></property>
</bean>
<!--student会自动找到下面这个bean对象,因为它的类与Student类中相关变量(book)对应的Book类相同,而无所谓它叫什么名字-->
<bean id="bookkkkkk" class="com.erwin.entity.Book">
<property name="ID" value="001"></property>
</bean>
</beans>
autowire="constructor"构造器方式自动注入
该方法事实上调用了内部对应的有参构造器,写起来很麻烦,很少使用,而且很容易造成阅读上的困惑。