自定义依赖注入注解实现@Autowired功能

通过自定义注解来实现注入功能有两种方法
第一种通过元注解的方式,在自定义注解上面用@Autowired标注既可以实现

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Autowired
public @interface MyAutowried {
}

第二种是通过向Spring中注册一个AutowiredAnnotationBeanPostProcessor实现,重点介绍第二种方式

public class DependencyResolutionDemo {

    @MyAutowried
    private User user;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        context.register(DependencyResolutionDemo.class);

        context.refresh();

        DependencyResolutionDemo bean = context.getBean(DependencyResolutionDemo.class);
        System.out.println(bean.user);

        context.close();
    }

    @Bean
    public User user() {
        User user = new User();
        user.setId(2L);
        return user;
    }
    

    @Bean
    public static AutowiredAnnotationBeanPostProcessor beanPostProcessor() {
        AutowiredAnnotationBeanPostProcessor postProcessor = new AutowiredAnnotationBeanPostProcessor();
        postProcessor.setAutowiredAnnotationType(MyAutowried.class);
        return postProcessor;
    }
}

上述代码可以在不影响原有实现的同时实现对自定义注解的扩展

原理

在Spring启动时,会获取类型为BeanPostProcessor.class的bean名称,然后获取对应Bean的实例,并加入beanFactory中的beanPostProcessors列表当中,代码流程如下

public static void registerBeanPostProcessors(
            ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
    
 
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

        int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
        beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

        List internalPostProcessors = new ArrayList<>();
        for (String ppName : postProcessorNames) {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                // 获取bean实例
                BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                if (pp instanceof MergedBeanDefinitionPostProcessor) {
                    // 将bean添加进集合
                    internalPostProcessors.add(pp);
                }
            }
        }
    // 对internalPostProcessors根据Order进行排序
    sortPostProcessors(internalPostProcessors, beanFactory);
    // 将processors添加进beanFactory的beanPostProcessors中
    registerBeanPostProcessors(beanFactory, internalPostProcessors);
    
}

// BeanFactory中的processors
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
        private final List beanPostProcessors = new CopyOnWriteArrayList<>();
   
}

对自定义注解的处理

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
        implements AutowireCapableBeanFactory {
    
    
    protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class beanType, String beanName) {
        // 获取beanFactory中所有的processor遍历处理
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                // 处理自定义注解相关依赖
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }
    
}



在创建 AutowiredAnnotationBeanPostProcessor 对象时,方法最好声明成静态方法,这样在Spring初始化该对象时就可以不用依赖它的外部对象

在该例中,如果beanPostProcessor() 方法不用static修饰,会造成User对象无法注入问题,

原因就在于Spring要先获取所有的AutowiredAnnotationBeanPostProcessor 对象,在执行beanPostProcessor()方法时需要先初始化其外部类 DependencyResolutionDemo,当初始化此对象时,就会对User对象开始注入,但是此时处理@MyAutowoired的注解处理器还没有初始化完成,就会造成@MyAutowoired 注解不能被处理

解决方法就是将beanPostProcessor()方法标注为static方法,或者将beanPostProcessor()单独写入另一个配置类当中

你可能感兴趣的:(自定义依赖注入注解实现@Autowired功能)