Spring的@Import注解

2024-01-01 23:05:40

@Import注解可以导入类,分为以下场景:

一、导入具体的类

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

二、导入一个ImportSelector类

@Import(MyImportSelector.class)
public class SpringConfig{
}
public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"com.cosseen.bean.Dog"};
    }
}

三、导入一个ImportBeanDefinitionRegistrar类

@Import(MyRegistrar.class)
public class SpringConfig{
}
public class MyRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Dog.class).getBeanDefinition();
        registry.registerBeanDefinition("dog", beanDefinition);
    }
}

四、导入一个BeanDefinitionRegistryPostProcessor类

@Import(MyPostProcessor.class)
public class SpringConfig{
}
public class MyPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Dog.class).getBeanDefinition();
        registry.registerBeanDefinition("dog", beanDefinition);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }
}

文章来源:https://blog.csdn.net/juxua_xatu/article/details/135329125
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。