SpringBoot自動裝配之Condition深入講解
Condition是在Spring 4.0 增加的條件判斷功能,通過這個可以功能可以實現(xiàn)選擇性的創(chuàng)建 Bean操作。
思考:
SpringBoot是如何知道要創(chuàng)建哪個Bean的?比如SpringBoot是如何知道要創(chuàng)建RedisTemplate的?
看一個例子:
當(dāng)我們沒導(dǎo)入redis-start時,會報錯
引出問題
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
問題:
SpringBoot是怎么知道我們導(dǎo)入redis坐標的呢?
案例一
需求:
在 Spring 的 IOC 容器中有一個 User 的 Bean,現(xiàn)要求:
通過condition設(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;
}
}測試:
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) {
//啟動SpringBoot應(yīng)用,返回Spring的IOC容器
ConfigurableApplicationContext context = SpringApplication.run(SpringbootDemo01Application.class, args);
Object user = context.getBean("user");
System.out.println(user);
}
}案例二
需求:
在 Spring 的 IOC 容器中有一個 User 的 Bean,現(xiàn)要求:
導(dǎo)入Jedis坐標后,加載該Bean,沒導(dǎo)入,則不加載。
新建User實體類:
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通過反射判斷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;
}
}測試類:
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) {
//啟動SpringBoot應(yīng)用,返回Spring的IOC容器
ConfigurableApplicationContext context = SpringApplication.run(SpringbootDemo01Application.class, args);
Object user = context.getBean("user");
System.out.println(user);
}
}引入jedis進行測試判斷:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.0</version>
</dependency>案例三
需求:
在 Spring 的 IOC 容器中有一個 User 的 Bean,現(xiàn)要求:
- 導(dǎo)入Jedis坐標后,加載該Bean,沒導(dǎo)入,則不加載。
- 將類的判斷定義為動態(tài)的。判斷哪個字節(jié)碼文件存在可以動態(tà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類:
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 上下文對象,用于獲取環(huán)境,ClassLoader對象
* @param metadata 注解的元對象,可以用于注解定義的屬性值
* @return
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
//1.需求:導(dǎo)入指定坐標后創(chuàng)建Bean
//思路:判斷指定坐標文件是否存在
//獲取注解屬性值 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;
}
}測試類:
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) {
//啟動SpringBoot應(yīng)用,返回Spring的IOC容器
ConfigurableApplicationContext context = SpringApplication.run(SpringbootDemo01Application.class, args);
Object user = context.getBean("user");
System.out.println(user);
}
}總結(jié)
自定義條件:
① 定義條件類:自定義類實現(xiàn)Condition接口,重寫 matches 方法,在 matches 方法中進行邏輯判斷,返回 boolean值 。 matches 方法兩個參數(shù):
- context:上下文對象,可以獲取屬性值,獲取類加載器,獲取BeanFactory等。
- metadata:元數(shù)據(jù)對象,用于獲取注解屬性。
② 判斷條件:在初始化Bean時,使用 @Conditional(條件類.class)注解
SpringBoot 提供的常用條件注解:
- ConditionalOnProperty:判斷配置文件中是否有對應(yīng)屬性和值才初始化Bean
@Bean
@ConditionalOnProperty(name = "com",havingValue = "example")
public User user1(){
return new User();
}配置文件添加一下屬性:
com = example
- ConditionalOnClass:判斷環(huán)境中是否有對應(yīng)字節(jié)碼文件才初始化Bean
- ConditionalOnMissingBean:判斷環(huán)境中沒有對應(yīng)Bean才初始化Bean
到此這篇關(guān)于SpringBoot自動裝配之Condition深入講解的文章就介紹到這了,更多相關(guān)SpringBoot Condition內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實現(xiàn)圖片上文字內(nèi)容的動態(tài)修改的操作步驟
在數(shù)字圖像處理領(lǐng)域,Java提供了強大的庫來處理圖片,包括讀取、修改和寫入圖片,如果你需要在Java應(yīng)用程序中修改圖片上的文字內(nèi)容,可以通過圖像處理技術(shù)來實現(xiàn),這篇博文將介紹如何使用Java實現(xiàn)圖片上文字內(nèi)容的動態(tài)修改,需要的朋友可以參考下2024-07-07
Java EE項目中的異常處理總結(jié)(一篇不得不看的文章)
什么是異常?運行時發(fā)生的可被捕獲和處理的錯誤。這篇文章主要介紹了Java EE項目中的異常處理總結(jié),有需要的可以了解一下。2016-11-11

