1. 程式人生 > >Spring的兩種依賴注入方式:setter方法注入與構造方法注入

Spring的兩種依賴注入方式:setter方法注入與構造方法注入

   Spring的兩種依賴注入方式:setter注入與構造方法注入,這兩種方法的不同主要就是在xml檔案下對應使用property和constructor-arg屬性, 例如:

property屬性:<property name="id" value="123"></property>(其中name的值為原類中的屬性名)

constructor-arg屬性:<constructor-arg index="0" value="456"></constructor-arg>(其中index的值為0~n-1,n代表建構函式中的輸入引數的數量)

1.setter方法注入

   setter方法注入即是建立一個普通的JavaBean類,為需要注入的屬性通過對應的setter方法即可,如:

(1)建立一個Id類:

package com.loster.li;

public class Id {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
(2)建立配置檔案Id_Bean.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-2.5.xsd">
           
	<bean id="id" class="com.loster.li.Id">
	<property name="id" value="123"></property>
	<property name="name" value="xiaoli"></property>
	</bean>
</beans>
(3)編寫測試類IdTest.java,並執行:
package com.loster.li;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class IdTest {
	public static void main(String[] args){
		ClassPathXmlApplicationContext context = new 
				ClassPathXmlApplicationContext("com/loster/li/Id_Bean.xml");
		
		Id id = (Id)context.getBean("id");
		System.out.println(id.getId());
		System.out.println(id.getName());
	}
}
   執行結果如下:

2.構造方法注入

(1)將上面的Id.class修改為:

package com.loster.li;

public class Id {
	private int id;
	private String name;
	public Id(int id,String name){
		this.id = id;
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
(2)將上面的Id_Bean.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-2.5.xsd">
           
	<bean id="id" class="com.loster.li.Id">
	<constructor-arg index="0" value="456"></constructor-arg>
	<constructor-arg index="1" value="dawang"></constructor-arg>
	</bean>
</beans>
(3)再次執行IdTest.java,執行結果如下: