SpringBoot中的ImportSelector類動態(tài)加載bean詳解
ImportSelector類動態(tài)加載bean
實現(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); } } }
結果
因為元數(shù)據(jù)上有@Configuration注解,所以返回的是cat
元數(shù)據(jù)上沒有@Configuration注解了,所以返回的是dog
總結
到此這篇關于SpringBoot中的ImportSelector類動態(tài)加載bean詳解的文章就介紹到這了,更多相關ImportSelector類動態(tài)加載bean內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot使用swagger-ui 2.10.5 有關版本更新帶來的問題小結
這篇文章主要介紹了springboot使用swagger-ui 2.10.5 有關版本更新帶來的問題小結,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12詳解spring boot starter redis配置文件
spring-boot-starter-Redis主要是通過配置RedisConnectionFactory中的相關參數(shù)去實現(xiàn)連接redis service。下面通過本文給大家介紹在spring boot的配置文件中redis的基本配置,需要的的朋友參考下2017-07-07Mybatis返回int或者Integer類型報錯的解決辦法
這篇文章主要介紹了Mybatis返回int或者Integer類型報錯的解決辦法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12Spring中DAO被循環(huán)調用的時候數(shù)據(jù)不實時更新的解決方法
這篇文章主要介紹了Spring中DAO被循環(huán)調用的時候數(shù)據(jù)不實時更新的解決方法,需要的朋友可以參考下2014-08-08