1. 程式人生 > 程式設計 >spring通過建構函式注入實現方法分析

spring通過建構函式注入實現方法分析

本文例項講述了spring通過建構函式注入實現方法。分享給大家供大家參考,具體如下:

一 通過建構函式注入

set注入的缺點是無法清晰表達哪些屬性是必須的,哪些是可選的,構造注入的優勢是通過構造強制依賴關係,不可能例項化不完全的或無法使用的bean。

二 舉例

1Employee

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;
    }
}

2beans.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>

3App1

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) 函式被呼叫..
大明

更多關於java相關內容感興趣的讀者可檢視本站專題:《Spring框架入門與進階教程》、《Java資料結構與演算法教程》、《Java操作DOM節點技巧總結》、《Java檔案與目錄操作技巧彙總》和《Java快取操作技巧彙總》

希望本文所述對大家java程式設計有所幫助。