最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

spring通過構造函數(shù)注入實現(xiàn)方法分析

 更新時間:2019年10月31日 11:29:14   作者:cakincqm  
這篇文章主要介紹了spring通過構造函數(shù)注入實現(xiàn)方法,結合實例形式分析了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ù)被調用..");
        this.name = name;
        this.age = age;
    }    
    public Employee(String name, int age) {
        System.out.println("Employee(String name, int age) 函數(shù)被調用..");
        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ù)被調用..
大明

更多關于java相關內(nèi)容感興趣的讀者可查看本站專題:《Spring框架入門與進階教程》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總

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

相關文章

最新評論

龙游县| 庆阳市| 沙洋县| 常宁市| 乳山市| 太保市| 通江县| 互助| 中江县| 新巴尔虎右旗| 静乐县| 蓬莱市| 美姑县| 友谊县| 仁寿县| 镇巴县| 德钦县| 波密县| 萍乡市| 贡嘎县| 马鞍山市| 甘孜县| 威海市| 华阴市| 张家界市| 曲水县| 同德县| 法库县| 宁德市| 锡林郭勒盟| 鞍山市| 乌兰县| 五莲县| 潮安县| 庆元县| 道真| 虎林市| 乐亭县| 黄陵县| 淅川县| 江源县|