DependsOn註解詳解

2021-10-23 13:52:00 字數 1660 閱讀 8052

@dependson註解可以定義在類和方法上,意思是我這個元件要依賴於另乙個元件,也就是說被依賴的元件會比該元件先註冊到ioc容器中。

比如老師是觀察者,學生是事件源,學生遲到是事件,老師觀察學生是否遲到,每當學生遲到,老師就會發現,並處罰該學生。

這類場景一般需要觀察者要比事件源先建立,才能不遺漏事件源觸發的每乙個事件,要是事件源先建立,可能會在觀察者建立前就觸發了事件而觀察者無法知道。

比如上述例子,八點算遲到,但是老師自己都八點半才到學校,所以就無法知道八點到八點半之間遲到的學生。

原始碼:

//可以作用在方法和類上。

//當作用在類上時,通常會與@component及其衍生註解等註解配合使用。

//當作用在方法上時,通常會與@bean註解配合使用。

@target()

@retention(retentionpolicy.runtime)

@documented

public @inte***ce dependson ;

}

demo(與@component配合使用)

/**

* 事件源

*/@component

public class eventsource

}/**

* 監聽類

*/@component

public class eventtlistener

}//測試類:

@configuration

@componentscan(basepackages = "dependsondemo")

public class springconfig

結果:

分析:因為spring預設掃瞄包時會根據檔案在資料夾的位置先後順序掃瞄載入,而eventsource 檔案位置在eventtlistener前面,所以會先載入eventsource 事件源元件。這不符合邏輯。

使用@dependson註解:

@component

@dependson(value = )

public class eventsource

}

結果:

***先建立了。value屬性的bean id必須存在,不然會報錯。

demo(與bean註解配合使用)

//要把上面兩個元件類上的註解去掉,再使用下面

@configuration

@componentscan(basepackages = "dependsondemo")

public class springconfig )

public eventsource eventsource()

@bean

public eventtlistener eventlistener()

}

結果:

如果不加@dependson註解的話,就會先建立事件源,如果加了(如上**),就會先建立***。

Jersey註解詳解

rest 中最重要的概念是資源 resources 使用全球 id 通常使用 uri 標識。客戶端應用程式使用 http 方法 get post put delete 操作資源或資源集。restful web 服務是使用 http 和 rest 原理實現的web 服務。通常,restful web ...

Spring 註解詳解

使用註解來構造ioc容器 在base package指明乙個包 表明com.om包及其子包中,如果某個類的頭上帶有特定的註解 component repository service controller 就會將這個物件作為bean註冊進spring容器。1 component component是...

Spring 註解詳解

當我們的專案越來越複雜時 配置檔案也會變得複雜 這樣不僅影響開發效率 還影響錯誤查詢 因此 spring 提供了註解方式開配置bean 使用註解需要準備工作 1.匯入 spring架包 2.引入約束檔案 context檔案 3.開啟掃瞄註解 常用註解 component 給user類加上該註解就等同...