Spring bean注入的方式

2021-09-01 16:27:03 字數 2551 閱讀 5136

一 setter方法注入

配置檔案如下:

action實現類中**:

private ihelloservice helloservice;

private string name ;

public void sayhello()

public void sethelloservice(ihelloservice helloservice)

public void setname(string name)

這裡的name和helloservice都採用屬性的setter方法注入。即類中設定乙個全域性屬性,並對屬性有setter方法,以供容器注入。

二 構造器注入

spring也支援構造器注入,也即有些資料中的構造子或者建構函式注入。

先看配置檔案:

action實現類中**:

private helloserviceimpl helloservice;

private string name ;

public springconstructorhelloaction(helloserviceimpl helloservice,string name)

@override

public void sayhello()同樣設定2個屬性,然後在建構函式中注入。

三靜態工廠注入

配置檔案如下:

action實現類:

private helloserviceimpl helloservice;

private string name = null;

private springfactoryhelloaction(string name ,helloserviceimpl helloservice)

public static springfactoryhelloaction createinstance(string name ,helloserviceimpl helloservice)

@override

public void sayhello()

四 無配置檔案注入(自動注入)

上面三種方法都需要編寫配置檔案,在spring2.5中還提供了不編寫配置檔案的ioc實現。需要注意的是,無配置檔案指bean之間依賴,不基於配置檔案,而不是指沒有spring配置檔案。

配置檔案如下:

<?xml version="1.0" encoding="utf-8"?>

可見上面只是設定了helloservice和helloaction兩個bean,並沒有設定helloaction對helloservice的依賴。

另外是必須的,有此才支援自動注入。

action實現類:

//屬性自動裝載,在屬性上加上 @autowired注釋,spring會自動注入helloservice

@autowired

private helloservice helloservice;

@override

public void sayhello()

//構造器自動注入:

@autowired

public springautowiredhelloaction(helloserviceimpl helloservice)

//setter方法自動注入:

@autowired

public void sethelloservice(helloservice helloservice)

最後在spring的reference文件中有提到,如果不使用自動注入,盡量使用setter方法,一般通用的也是使用setter方法。

而使用自動注入還是配置檔案方式,如果jdk低於1.5或者spring不是2.5,就只能夠使用配置檔案方式了。其它的就看實際專案選擇了。

@resource和@autowire的區別

使用@autowire或者@resource註解方式進行裝配,這兩個註解的區別是:

@autowire預設按照型別裝配,預設情況下它要求依賴物件必須存在如果允許為null,可以設定它required屬性為false,如果我們想使用按照名稱裝配,可以結合@qualifier註解一起使用;

@resource預設按照名稱裝配,當找不到與名稱匹配的bean才會按照型別裝配,可以通過name屬性指定,如果沒有指定name屬性,當註解標註在字段上,即預設取字段的名稱作為bean名稱尋找依賴物件,當註解標註在屬性的setter方法上,即預設取屬性名作為bean名稱尋找依賴物件.

注意:如果沒有指定name屬性,並且按照預設的名稱仍然找不到依賴的物件時候,會回退到按照型別裝配,但一旦指定了name屬性,就只能按照名稱裝配了

04 Spring Bean注入方式

實現ioc容器主要有兩種方式 1,依賴查詢 2,依賴注入,spring採用的是依賴注入的方式 依賴注入又分為3種方式 2.1 構造器注入 2.2 setter注入 2.3 介面注入 構造器注入和setter注入背後都是採用反射的技術來實現。介面注入,通常是指資源並非來自系統自身,而是來自系統外。比如...

SPRING BEAN的4種依賴注入方式

所謂依賴注入,其實就是給物件裡的屬性賦值,因為物件裡有其他物件,因此就形成了依賴。spring有4種方式來給屬性賦值 1.構造方法注入 2.set方法注入 3.自動裝配 4.註解構造方法注入是指在構造方法中注入屬性或者物件來實現依賴注入,如下所示,在標籤中定義乙個id為userdaoimpl的bea...

Spring Bean的注入有簡單的方式嗎?

註解方式注入 對於bean的注入,除了使用xml配置以外,註解的配置簡化開發的速度,使程式看上去更加簡潔。對於註解的解釋,spring對於註解有專門的直譯器,對定義的註解進行解析,實現對應bean物件的注入,反射技術實現。1.加入spring aop jar包spring aop 4.3.2.rel...