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起步依賴(lài)后
<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í)體類(lèi):
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í)體類(lèi):
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è)試類(lèi):
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)入,則不加載。
- 將類(lèi)的判斷定義為動(dòng)態(tài)的。判斷哪個(gè)字節(jié)碼文件存在可以動(dòng)態(tài)指定。
實(shí)體類(lèi):
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類(lèi):
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();
}配置類(lèi):
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è)試類(lèi):
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é)
自定義條件:
① 定義條件類(lèi):自定義類(lèi)實(shí)現(xiàn)Condition接口,重寫(xiě) matches 方法,在 matches 方法中進(jìn)行邏輯判斷,返回 boolean值 。 matches 方法兩個(gè)參數(shù):
- context:上下文對(duì)象,可以獲取屬性值,獲取類(lèi)加載器,獲取BeanFactory等。
- metadata:元數(shù)據(jù)對(duì)象,用于獲取注解屬性。
② 判斷條件:在初始化Bean時(shí),使用 @Conditional(條件類(lèi).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 獲取本機(jī)的IP與MAC地址實(shí)現(xiàn)詳解
這篇文章主要介紹了Java 獲取本機(jī)的IP與MAC地址實(shí)現(xiàn)詳解的相關(guān)資料,需要的朋友可以參考下2016-09-09
java的Object里wait()實(shí)現(xiàn)原理講解
這篇文章主要介紹了java的Object里wait()實(shí)現(xiàn)原理,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
全面剖析java 數(shù)據(jù)類(lèi)型與運(yùn)算符
這篇文章主要介紹了Java基本數(shù)據(jù)類(lèi)型和運(yùn)算符,結(jié)合實(shí)例形式詳細(xì)分析了java基本數(shù)據(jù)類(lèi)型、數(shù)據(jù)類(lèi)型轉(zhuǎn)換、算術(shù)運(yùn)算符、邏輯運(yùn)算符等相關(guān)原理與操作技巧,需要的朋友可以參考下2021-09-09
SpringBoot之HttpWebServiceMessageSenderBuilder用法詳解
這篇文章主要介紹了SpringBoot之HttpWebServiceMessageSenderBuilder用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-04-04
maven中自定義MavenArchetype的實(shí)現(xiàn)
Maven自身提供了許多Archetype來(lái)方便用戶(hù)創(chuàng)建Project,為了避免在創(chuàng)建project時(shí)重復(fù)的拷貝和修改,我們通過(guò)自定義Archetype來(lái)規(guī)范顯得還蠻有必要,下面就來(lái)介紹一下,感興趣的可以了解一下2025-01-01
MyEclipse2018中安裝Mybatis generator插件的實(shí)現(xiàn)步驟
這篇文章主要介紹了MyEclipse2018中安裝Mybatis generator插件的實(shí)現(xiàn)步驟,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-02-02
java實(shí)現(xiàn)百度云文字識(shí)別接口代碼
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)百度云文字識(shí)別的接口代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11
使用SpringBoot進(jìn)行身份驗(yàn)證和授權(quán)的示例詳解
在廣闊的 Web 開(kāi)發(fā)世界中,身份驗(yàn)證是每個(gè)數(shù)字領(lǐng)域的守護(hù)者,在本教程中,我們將了解如何以本機(jī)方式保護(hù)、驗(yàn)證和授權(quán) Spring-Boot 應(yīng)用程序的用戶(hù),并遵循框架的良好實(shí)踐,希望對(duì)大家有所幫助2023-11-11

