spring--Autowired setter 方法
在Spring中,可以使用 @Autowired 注解通过setter方法,构造函数或字段自动装配Bean。此外,它可以在一个特定的bean属性自动装配。
注 @Autowired注解是通过匹配数据类型自动装配Bean。
package Autowired; /** * Created by luozhitao on 2017/8/9. */ public class person1 { public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAdress() { return adress; } public void setAdress(String adress) { this.adress = adress; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } private String name; private String adress; private int age; }
package Autowired; import org.springframework.beans.factory.annotation.Autowired; /** * Created by luozhitao on 2017/8/9. */ public class Customer1 { public int getType() { return type; } public void setType(int type) { this.type = type; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public person1 getPerson() { return person; } @Autowired public void setPerson(person1 person) { this.person = person; } private int type; private String action; private person1 person; }
<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" 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"> <context:annotation-config /> <bean id="person" class="Autowired.person1"> <property name="name" value="猫儿"/> <property name="adress" value="beijing"/> <property name="age" value="1"/> </bean> <bean id="customer" class="Autowired.Customer1"> <property name="type" value="2"/> <property name="action" value="buy"/> </bean> </beans>
通过构造方法注入:
package Autowired; import org.springframework.beans.factory.annotation.Autowired; /** * Created by luozhitao on 2017/8/9. */ public class Customer2 { public int getType() { return type; } public void setType(int type) { this.type = type; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public person1 getPerson() { return person; } public void setPerson(person1 person) { this.person = person; } private int type; private String action; private person1 person; @Autowired public Customer2(person1 person){ this.person=person; } }
通过字段进行注入:
package Autowired; import org.springframework.beans.factory.annotation.Autowired; /** * Created by luozhitao on 2017/8/9. */ public class Customer3 { public int getType() { return type; } public void setType(int type) { this.type = type; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public person1 getPerson() { return person; } private int type; private String action; @Autowired private person1 person; }