這篇文章給大家介紹怎么在spring中通過構造函數注入,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
一 通過構造函數注入
set注入的缺點是無法清晰表達哪些屬性是必須的,哪些是可選的,構造注入的優勢是通過構造強制依賴關系,不可能實例化不完全的或無法使用的bean。
二 舉例
1 Employee
package com.hsp.constructor;
public class Employee {
private String name;
private int age;
public Employee(String name) {
System.out.println("Employee(String name) 函數被調用..");
this.name = name;
this.age = age;
}
public Employee(String name, int age) {
System.out.println("Employee(String name, int age) 函數被調用..");
this.name = name;
this.age = 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;
}
}2 beans.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"; xmlns:context="http://www.springframework.org/schema/context"; xmlns:tx="http://www.springframework.org/schema/tx"; xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsd";> <!-- 配置一個雇員對象 --> <bean id="employee" class="com.hsp.constructor.Employee"> <!-- 通過構造函數來注入屬性值 --> <constructor-arg index="0" type="java.lang.String" value="大明" /> </bean> </beans>
3 App1
package com.hsp.constructor;
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/constructor/beans.xml");
Employee ee=(Employee) ac.getBean("employee");
System.out.println(ee.getName());
}
}三 測試結果
Employee(String name) 函數被調用..
大明
關于怎么在spring中通過構造函數注入就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。