SpringBoot中的ImportSelector類動態(tài)加載bean詳解
ImportSelector類動態(tài)加載bean
實(shí)現(xiàn)ImportSelector類→ 動態(tài)加載bean → 源碼中大量使用
代碼
package com.qing.config;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import java.util.Map;
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata metadata) {
//metadata元數(shù)據(jù) : 指的是加載本類MyImportSelector的類
//metadata的get、has、is 有大量方法,可以用來獲取判斷數(shù)據(jù)
Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes("org.springframework.context.annotation.ComponentScan");
System.out.println("注解"+annotationAttributes);
boolean hasConfiguration = metadata.hasAnnotation("org.springframework.context.annotation.Configuration");
if(hasConfiguration){
return new String[]{"com.qing.bean.cat"};
}
return new String[]{"com.qing.bean.dog"};
}
}元數(shù)據(jù)metadata指的是下面的config6
package com.qing.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
//@Configuration 注解是測試用的
@Configuration
//@ComponentScan 注解是測試用的
@ComponentScan("com.qing.bean")
@Import(MyImportSelector.class)
public class SpringConfig6 {
}測試
package com.qing.app;
import com.qing.config.SpringConfig6;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App6 {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig6.class);
String[] names = ctx.getBeanDefinitionNames();
for (String name : names) {
System.out.println("bean的名字:" + name);
}
}
}結(jié)果
因?yàn)樵獢?shù)據(jù)上有@Configuration注解,所以返回的是cat

元數(shù)據(jù)上沒有@Configuration注解了,所以返回的是dog

總結(jié)

到此這篇關(guān)于SpringBoot中的ImportSelector類動態(tài)加載bean詳解的文章就介紹到這了,更多相關(guān)ImportSelector類動態(tài)加載bean內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)自動把報表插入到word文檔中
在很多業(yè)務(wù)場景中需要在 word 文檔中嵌入報表,這篇文章主要為大家介紹了如何使用Java實(shí)現(xiàn)自動把報表插入到word文檔中,需要的可以參考下2024-12-12
springboot使用swagger-ui 2.10.5 有關(guān)版本更新帶來的問題小結(jié)
這篇文章主要介紹了springboot使用swagger-ui 2.10.5 有關(guān)版本更新帶來的問題小結(jié),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
詳解spring boot starter redis配置文件
spring-boot-starter-Redis主要是通過配置RedisConnectionFactory中的相關(guān)參數(shù)去實(shí)現(xiàn)連接redis service。下面通過本文給大家介紹在spring boot的配置文件中redis的基本配置,需要的的朋友參考下2017-07-07
Mybatis返回int或者Integer類型報錯的解決辦法
這篇文章主要介紹了Mybatis返回int或者Integer類型報錯的解決辦法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12
Spring中DAO被循環(huán)調(diào)用的時候數(shù)據(jù)不實(shí)時更新的解決方法
這篇文章主要介紹了Spring中DAO被循環(huán)調(diào)用的時候數(shù)據(jù)不實(shí)時更新的解決方法,需要的朋友可以參考下2014-08-08

