普通類
@Configuration @Import(OtherBean.class) public class SpringConfig { }
public class OtherBean { }
ImportSelector實現類
實現類不會被註冊成Bean,介面方法的返回值會被註冊成Bean。【BeanName是全類名】
@Configuration @Import(MyImportSelector.class) public class SpringConfig { }
public class MyImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{OtherBean.class.getName()}; } }
DeferredImportSelector實現類
@Configuration @Import(MyDeferredImportSelector.class) public class SpringConfig { }
public class MyDeferredImportSelector implements DeferredImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{OtherBean.class.getName()}; } }
ImportBeanDefinitionRegistrar實現類
實現類不會被註冊為bean,但是會回撥其介面方法,由開發者通過Spring api手動向Spring容器註冊bean。【類似於BeanFactoryPostRegister】
@Configuration @Import(MyImportBeanDefinitionRegistrar.class) public class SpringConfig { }
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { BeanDefinition beanDefinition = new RootBeanDefinition(); String beanName = StringUtils.uncapitalize(OtherBean.class.getSimpleName()); beanDefinition.setBeanClassName(OtherBean.class.getName()); registry.registerBeanDefinition(beanName,beanDefinition); } }