SpringBoot自動(dòng)裝配之Condition深入講解
Condition是在Spring 4.0 增加的條件判斷功能,通過(guò)這個(gè)可以功能可以實(shí)現(xiàn)選擇性的創(chuàng)建 Bean操作。
思考:
SpringBoot是如何知道要?jiǎng)?chuàng)建哪個(gè)Bean的?比如SpringBoot是如何知道要?jiǎng)?chuàng)建RedisTemplate的?
看一個(gè)例子:
當(dāng)我們沒(méi)導(dǎo)入redis-start時(shí),會(huì)報(bào)錯(cuò)
引出問(wèn)題
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'redisTemplate' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:874) at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1358) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) at com.example.condition.SpringbootDemo01Application.main(SpringbootDemo01Application.java:13)
當(dāng)導(dǎo)入redis起步依賴后
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
org.springframework.data.redis.core.RedisTemplate@5a6d5a8f
問(wèn)題:
SpringBoot是怎么知道我們導(dǎo)入redis坐標(biāo)的呢?
案例一
需求:
在 Spring 的 IOC 容器中有一個(gè) User 的 Bean,現(xiàn)要求:
通過(guò)condition設(shè)置加載或者不加載。
新建實(shí)體類:
package com.example.condition.entity; public class User { }
新建配置文件:
package com.example.condition.config; import com.example.condition.condition.ClassCondition; import com.example.condition.entity.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration public class UserConfig { @Bean @Conditional(ClassCondition.class) public User user(){ return new User(); } }
新建condition:
如果為true則加載,如果為false則不加載
package com.example.condition.condition; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class ClassCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return true; } }
測(cè)試:
package com.example.condition; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class SpringbootDemo01Application { public static void main(String[] args) { //啟動(dòng)SpringBoot應(yīng)用,返回Spring的IOC容器 ConfigurableApplicationContext context = SpringApplication.run(SpringbootDemo01Application.class, args); Object user = context.getBean("user"); System.out.println(user); } }
案例二
需求:
在 Spring 的 IOC 容器中有一個(gè) User 的 Bean,現(xiàn)要求:
導(dǎo)入Jedis坐標(biāo)后,加載該Bean,沒(méi)導(dǎo)入,則不加載。
新建User實(shí)體類:
package com.example.condition.entity; public class User { }
新建配置文件:
package com.example.condition.config; import com.example.condition.condition.ClassCondition; import com.example.condition.entity.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration public class UserConfig { @Bean @Conditional(ClassCondition.class) public User user(){ return new User(); } }
condition通過(guò)反射判斷jedis是否已經(jīng)加載完畢
package com.example.condition.condition; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class ClassCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { boolean flag =true; try { Class<?> cls = Class.forName("redis.clients.jedis.Jedis"); }catch (ClassNotFoundException e){ flag =false; } return flag; } }
測(cè)試類:
package com.example.condition; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class SpringbootDemo01Application { public static void main(String[] args) { //啟動(dòng)SpringBoot應(yīng)用,返回Spring的IOC容器 ConfigurableApplicationContext context = SpringApplication.run(SpringbootDemo01Application.class, args); Object user = context.getBean("user"); System.out.println(user); } }
引入jedis進(jìn)行測(cè)試判斷:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.6.0</version> </dependency>
案例三
需求:
在 Spring 的 IOC 容器中有一個(gè) User 的 Bean,現(xiàn)要求:
- 導(dǎo)入Jedis坐標(biāo)后,加載該Bean,沒(méi)導(dǎo)入,則不加載。
- 將類的判斷定義為動(dòng)態(tài)的。判斷哪個(gè)字節(jié)碼文件存在可以動(dòng)態(tài)指定。
實(shí)體類:
package com.example.condition.entity; public class User { }
自定義注解:
package com.example.condition.condition;import org.springframework.context.annotation.Conditional;import java.lang.annotation.*;@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documented@Conditional(ClassCondition.class)public @interface ConditionOnClass { String[] value();}
Condition類:
package com.example.condition.condition; import org.springframework.context.annotation.Conditional; import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Conditional(ClassCondition.class) public @interface ConditionOnClass { String[] value(); }
配置類:
package com.example.condition.condition; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotatedTypeMetadata; import java.util.Map; public class ClassCondition implements Condition { /** * @param context 上下文對(duì)象,用于獲取環(huán)境,ClassLoader對(duì)象 * @param metadata 注解的元對(duì)象,可以用于注解定義的屬性值 * @return */ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); //1.需求:導(dǎo)入指定坐標(biāo)后創(chuàng)建Bean //思路:判斷指定坐標(biāo)文件是否存在 //獲取注解屬性值 value Map<String, Object> map = metadata.getAnnotationAttributes(ConditionOnClass.class.getName()); String[] value = (String[]) map.get("value"); boolean flag = true; try { for (String className : value) { Class<?> cls = Class.forName(className); } } catch (ClassNotFoundException e) { flag = false; } return flag; } }
測(cè)試類:
package com.example.condition; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class SpringbootDemo01Application { public static void main(String[] args) { //啟動(dòng)SpringBoot應(yīng)用,返回Spring的IOC容器 ConfigurableApplicationContext context = SpringApplication.run(SpringbootDemo01Application.class, args); Object user = context.getBean("user"); System.out.println(user); } }
總結(jié)
自定義條件:
① 定義條件類:自定義類實(shí)現(xiàn)Condition接口,重寫(xiě) matches 方法,在 matches 方法中進(jìn)行邏輯判斷,返回 boolean值 。 matches 方法兩個(gè)參數(shù):
- context:上下文對(duì)象,可以獲取屬性值,獲取類加載器,獲取BeanFactory等。
- metadata:元數(shù)據(jù)對(duì)象,用于獲取注解屬性。
② 判斷條件:在初始化Bean時(shí),使用 @Conditional(條件類.class)注解
SpringBoot 提供的常用條件注解:
- ConditionalOnProperty:判斷配置文件中是否有對(duì)應(yīng)屬性和值才初始化Bean
@Bean @ConditionalOnProperty(name = "com",havingValue = "example") public User user1(){ return new User(); }
配置文件添加一下屬性:
com = example
- ConditionalOnClass:判斷環(huán)境中是否有對(duì)應(yīng)字節(jié)碼文件才初始化Bean
- ConditionalOnMissingBean:判斷環(huán)境中沒(méi)有對(duì)應(yīng)Bean才初始化Bean
到此這篇關(guān)于SpringBoot自動(dòng)裝配之Condition深入講解的文章就介紹到這了,更多相關(guān)SpringBoot Condition內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java使用HashMap實(shí)現(xiàn)斗地主(有序版)
這篇文章主要為大家詳細(xì)介紹了java使用ArrayList實(shí)現(xiàn)斗地主游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-03-03Java實(shí)現(xiàn)圖片上文字內(nèi)容的動(dòng)態(tài)修改的操作步驟
在數(shù)字圖像處理領(lǐng)域,Java提供了強(qiáng)大的庫(kù)來(lái)處理圖片,包括讀取、修改和寫(xiě)入圖片,如果你需要在Java應(yīng)用程序中修改圖片上的文字內(nèi)容,可以通過(guò)圖像處理技術(shù)來(lái)實(shí)現(xiàn),這篇博文將介紹如何使用Java實(shí)現(xiàn)圖片上文字內(nèi)容的動(dòng)態(tài)修改,需要的朋友可以參考下2024-07-07Java EE項(xiàng)目中的異常處理總結(jié)(一篇不得不看的文章)
什么是異常?運(yùn)行時(shí)發(fā)生的可被捕獲和處理的錯(cuò)誤。這篇文章主要介紹了Java EE項(xiàng)目中的異常處理總結(jié),有需要的可以了解一下。2016-11-11Java實(shí)現(xiàn)視頻時(shí)間維度剪切的工具類
這篇文章主要為大家詳細(xì)介紹了將視頻按照時(shí)間維度進(jìn)行剪切的Java工具類,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12Json傳輸出現(xiàn)中文亂碼問(wèn)題的解決辦法
最近遇到一個(gè)問(wèn)題,就是將中文消息以json格式推給微信服務(wù)器時(shí),收到的消息是亂碼,所以下面這篇文章主要給大家介紹了關(guān)于Json傳輸出現(xiàn)中文亂碼問(wèn)題的解決辦法,需要的朋友可以參考下2023-05-05Java自動(dòng)釋放鎖的三種實(shí)現(xiàn)方案
在筆者面試過(guò)程時(shí),經(jīng)常會(huì)被問(wèn)到各種各樣的鎖,如樂(lè)觀鎖、讀寫(xiě)鎖等等,非常繁多,下面這篇文章主要給大家介紹了關(guān)于Java自動(dòng)釋放鎖的三種實(shí)現(xiàn)方案,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06servlet異步請(qǐng)求的實(shí)現(xiàn)
本文主要介紹了servlet異步請(qǐng)求的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07