天天看點

使用ImportSelector接口動态加載Bean

作者:長頸鹿睡覺

Spring架構提供了ImportSelector接口來實作根據條件動态加載Bean。

這種方式在做架構開發的時候經常會用到。

建立ImportSelector接口的實作類

在實作類中實作接口方法selectImports,并在return的數組中添加期望建立為Bean的全路徑類名。

public class TestImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"com.test.entity.User"};
    }
}           

使用@Import加載實作類

在Spring配置類中使用@Import加載ImportSelector接口實作類。

@Import(TestImportSelector.class)
public class SpringConfig {
}           

加載Spring配置

使用上下文對象加載Spring配置類,列印Spring容器中的Bean名稱,能看到ImportSelector接口實作類中配置的Bean已經生效。

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
String[] names = context.getBeanDefinitionNames();
for (String n : names){
    System.out.println(n);
}           
使用ImportSelector接口動态加載Bean

動态加載Bean

ImportSelector接口的優勢是可以通過Spring配置類的動态屬性,自由進行Bean的加載。

在ImportSelector接口的方法selectImports中,有一個參數AnnotationMetadata,通過這個參數可以擷取Spring配置類的相關屬性,開發人員根據這些屬性,動态選擇需要加載的Bean、

使用ImportSelector接口動态加載Bean

如下示例,列印了Spirng配置類的類名和在配置類上使用的注解類型。

public class TestImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        System.out.println("------------------------------");
        System.out.println(importingClassMetadata.getClassName());
        System.out.println(importingClassMetadata.getAnnotationTypes());
        System.out.println("------------------------------");
        return new String[]{"com.test.entity.User"};
    }
}           
使用ImportSelector接口動态加載Bean

繼續閱讀