Spring中Aware系列介面

2021-08-04 14:45:00 字數 1460 閱讀 9944

(一)ioc容器管理bean,bean在ioc容器中。那麼bean知不知道自己在ioc容器中的代號(id)呢?bean知不知道自己在哪個ioc容器中?能否通過bean獲取它的ioc容器物件呢?簡單來說就是:bean是否對spring有知覺

答:單純的bean(未實現aware系列介面)是沒有知覺的;實現了aware系列介面的bean可以訪問spring容器。

這些aware系列介面增強了spring bean的功能,但是也會造成對spring框架的繫結,增大了與spring框架的耦合度。

(aware是「意識到的,察覺到的」的意思,實現了aware系列介面表明:可以意識到、可以察覺到)

(二)首先,看一下aware系列介面

(三)aware系列介面的共性

(1)都以「aware」結尾

(2)都是aware介面的子介面,即都繼承了aware介面

(3)介面內均定義了乙個set方法

(四)aware系列介面的set方法

(1)父介面aware中沒有定義任何方法,只是乙個標識介面

public

inte***ce aware

public

inte***ce

extends

aware

beannameaware介面:

public

inte***ce

beannameaware

extends

aware

beanclassloaderaware介面:

public

inte***ce

beanclassloaderaware

extends

aware

//實現beannameaware介面,才能獲取bean在ioc容器中的id

public

class

helloworld

implements

beannameaware

public string getbeanname()

}

在 bean配置檔案中,註冊乙個id為「hello」的bean:

class="com.helloworld"

id="hello">

bean>

public

static

void

main(string args)

輸出結果:

hello

Spring中的Aware介面

spring中提供了一些以aware結尾的介面,實現了aware介面的bean在被初始化後,可以獲取相應資源。通過aware介面,可以對spring相應資源進行操作 一定要慎重,因為可能修改spring核心類 aware有以下介面 介面作用 beannameaware 在bean中得到它在ioc容器...

Spring中的Aware介紹

如果需要獲取到spring中容器或者其他spring中資源的時候,我們就需要實現aware一系列的介面,這樣才能獲取到。spring中常用的aware介面 beannameaware 獲得到容器中bean的名稱 beanfactoryaware 獲得當前bean factory,從而呼叫容器的服務 ...

Spring中Aware介面的使用

第一步 配置xml,並實現要繼承的2個類和測試類 xml xmlns xsi schemalocation package com.imooc.aware 繼承beannameaware的類 package com.imooc.aware import org.springframework.bea...