spring通過構造函數(shù)注入實現(xiàn)方法分析
本文實例講述了spring通過構造函數(shù)注入實現(xiàn)方法。分享給大家供大家參考,具體如下:
一 通過構造函數(shù)注入
set注入的缺點是無法清晰表達哪些屬性是必須的,哪些是可選的,構造注入的優(yōu)勢是通過構造強制依賴關系,不可能實例化不完全的或無法使用的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) 函數(shù)被調(diào)用..");
this.name = name;
this.age = age;
}
public Employee(String name, int age) {
System.out.println("Employee(String name, int age) 函數(shù)被調(diào)用..");
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">
<!-- 通過構造函數(shù)來注入屬性值 -->
<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) 函數(shù)被調(diào)用..
大明
更多關于java相關內(nèi)容感興趣的讀者可查看本站專題:《Spring框架入門與進階教程》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
Java數(shù)據(jù)類型Integer與int的區(qū)別詳細解析
這篇文章主要介紹了Java數(shù)據(jù)類型Integer與int的區(qū)別詳細解析,Ingeter是int的包裝類,int的初值為0,Ingeter的初值為null,int和integer(無論new否)比,都為true,因為會把Integer自動拆箱為int再去比,需要的朋友可以參考下2023-12-12
spring?boot配置dubbo方式(properties)
這篇文章主要介紹了spring?boot配置dubbo方式(properties),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
Spring的@ConfigurationProperties注解詳解
這篇文章主要介紹了Spring的@ConfigurationProperties注解詳解,@ConfigurationProperties該注解是用來獲取yml或者properties配置文件的配置信息,下面根據(jù)一些配置信息給出案例代碼進行講解,需要的朋友可以參考下2023-11-11
java基于Des對稱加密算法實現(xiàn)的加密與解密功能詳解
這篇文章主要介紹了java基于Des對稱加密算法實現(xiàn)的加密與解密功能,結合實例形式詳細分析了Des加密算法的功能、原理、使用方法與相關注意事項,需要的朋友可以參考下2017-01-01
Java Socket編程簡介_動力節(jié)點Java學院整理
這篇文章主要介紹了Java Socket編程簡介的相關知識,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-05-05

