Spring的@Import注解

@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 {

    }
}

你可能感兴趣的:(spring,java,后端)