Conditional載入探索

2021-10-01 17:14:53 字數 2407 閱讀 6321

spring boot 或者spring將所有持有模式註解的類元資料,掃瞄到容器中,然後通過條件註解

conditionalonbean篩選可用的bean,去除不合條件的bean(刪除定義)。

此時會出現如下結果

1.先載入(loadbeandefinitions)testlifecomponent 然後載入testconfiguration,那麼這兩個類都無法成為容器bean

2.先載入(loadbeandefinitions)testconfiguration 然後載入testlifecomponent ,那麼testconfiguration 可成為容器bean

本質上如果testconfiguration先進行

loadbeandefinitionsforconfigurationclass,那麼此時容器中含有testlifecomponent的定義,就可以順利進行載入;反之 testlifecomponent先進行載入,那麼此時找name為testconfiguration1的bean定義,那麼就會因為不合條件,而被skip掉,並且刪除本身在容器中的定義。

public void loadbeandefinitions(setconfigurationmodel) 

}

@slf4j

@component

//即使testlifecomponent曇花一現,testconfiguration也可以被載入上。

@conditionalonbean(name = "testlifecomponent")

public class testconfiguration implements beanfactoryaware, beanclassloaderaware, environmentaware, beanfactorypostprocessor ";

static

public int i = 0;

public testconfiguration()

@override

public void setbeanfactory(beanfactory beanfactory) throws bean***ception

@override

public void setbeanclassloader(classloader classloader)

@override

public void postprocessbeanfactory(configurablelistablebeanfactory beanfactory) throws bean***ception

@override

public void setenvironment(environment environment)

}

@slf4j

@component

@conditionalonbean(name = "testconfiguration1")

public class testlifecomponent implements beanfactoryaware, beanclassloaderaware, environmentaware, beanfactorypostprocessor, beanpostprocessor ";

static

public int i = 0;

public testlifecomponent()

@override

public void setbeanfactory(beanfactory beanfactory) throws bean***ception

@override

public void setbeanclassloader(classloader classloader)

@override

public void postprocessbeanfactory(configurablelistablebeanfactory beanfactory) throws bean***ception

@override

public object postprocessbeforeinitialization(object bean, string beanname) throws bean***ception

@override

public object postprocessafterinitialization(object bean, string beanname) throws bean***ception

@override

public void setenvironment(environment environment)

}

條件註解 Conditional

可以讓某乙個bean 在某些條件下 加入ioc容器,其他情況下不加ioc容器。a.準備普通bean b.增加條件bean 給每個bean設定條件,必須實現condition介面 如 oilcarcondition類 public class oilcarcondition implements co...

Conditional註解分析

我們需要bean在滿足一定條件下才允許注入spring容器的情況,可以加註 conditional註解。加註了此註解的bean在定義被spring註冊前會被條件判斷。自定義註解標註 conditional也不允許宣告為 inherited。target retention retentionpoli...

Conditional註解使用

conditional spring4.0 介紹了乙個新的註解 conditional,它的邏輯語義可以作為 if then else 來對bean的註冊起作用。source code recreated from a class file by intellij idea powered by f...