Spring高階話題 Aware

2021-10-01 08:41:00 字數 2246 閱讀 1599

一、aware是什麼?

spring aware就是一些定義了spring容器本身功能資源的介面

spring提供的aware介面

介面備註

beannameaware

獲得到容器中bean的名稱

beanfactoryaware

獲得當前 bean factory,這樣可以呼叫容器的服務

messagesourceaware

獲得 message source,這樣可以獲得文字資訊

應用事件發布器,可以發布事件

resourceloaderaware

獲得資源載入器,可以獲得外部資源檔案

二、什麼時候用aware

當某乙個bean需要獲得spring容器的服務時,可以實現對應的aware介面。

注意: 這樣會造成bean與spring框架的耦合性增加

三、awaredemo

bean

package com.cactus.demo.aware;

import org.apache.commons.io.ioutils;

import org.springframework.beans.factory.beannameaware;

import org.springframework.context.resourceloaderaware;

import org.springframework.core.io.resource;

import org.springframework.core.io.resourceloader;

import org.springframework.stereotype.service;

/** * created by liruigao

* date: 2019-12-05 14:35

* description:

*/@service

public

class

awaredemo

implements

beannameaware

, resourceloaderaware

public

void

setresourceloader

(resourceloader resourceloader)

public

void

show()

catch

(exception e)

}}

配置類

package com.cactus.demo.aware;

import org.springframework.context.annotation.componentscan;

import org.springframework.context.annotation.configuration;

/** * created by liruigao

* date: 2019-12-05 14:43

* description:

*/@configuration

@componentscan

("com.cactus.demo.aware"

)public

class

awareconfig

awaredemo.txt

this is a awaredemo!
main

package com.cactus.demo.aware;

/** * created by liruigao

* date: 2019-12-05 14:45

* description:

*/public

class

main

}

result

beanname : awaredemo

resource desc : class path resource [awaredemo/awaredemo.txt]

resource streamstr : this is a awaredemo!

Spring高階話題 條件註解

一 什麼是條件註解根據特定的條件來控制bean的建立行為 使用到的註解 conditional 二 如何使用條件註解通過實現condition介面並重寫matches方法 構造判斷條件 來實現乙個條件判斷類 在配置bean時使用 conditional註解,並指定條件判斷類,實現有條件地建立bean...

Spring中的Aware介面

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

Spring中Aware系列介面

一 ioc容器管理bean,bean在ioc容器中。那麼bean知不知道自己在ioc容器中的代號 id 呢?bean知不知道自己在哪個ioc容器中?能否通過bean獲取它的ioc容器物件呢?簡單來說就是 bean是否對spring有知覺 答 單純的bean 未實現aware系列介面 是沒有知覺的 實...