Spring加载后置处理器方式之模板方法

Spring加载后置处理器方式之模板方法

  • 1. 未使用模板方法时
  • 2. 使用模板方法后

1. 未使用模板方法时

 public static void main(String[] args) {

        MyBeanFactory myBeanFactory = new MyBeanFactory();
        myBeanFactory.getBean();
    }

    static class MyBeanFactory {
        public Object getBean() {

            Object bean = new Object();
            System.out.println("构造...." + bean);
            System.out.println("依赖注入...." + bean);
            //需在此手动加载,代码高度耦合
            System.out.println("初始化...." + bean);
            return bean;
        }

    }

2. 使用模板方法后

仅需在生成对象后添加后置处理器,对MyBeanFactory无需修改,实现代码解耦和

 public static void main(String[] args) {

        MyBeanFactory myBeanFactory = new MyBeanFactory();
        myBeanFactory.addBeanPostProcessor(bean -> {
            System.out.println("解析了@Autowired");
        });
        myBeanFactory.addBeanPostProcessor(bean -> {
            System.out.println("解析了@Resource");
        });
        myBeanFactory.getBean();
    }

    static class MyBeanFactory {
        public Object getBean() {

            Object bean = new Object();
            System.out.println("构造...." + bean);
            System.out.println("依赖注入...." + bean);
            beanPostProcessors.forEach(i -> {
                i.inject(bean);
            });
            System.out.println("初始化...." + bean);
            return bean;
        }

        private List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

        public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
            beanPostProcessors.add(beanPostProcessor);
        }

    }

    static interface BeanPostProcessor {
        //增强依赖注入阶段,解析@Autowired @Resource注解
        public void inject(Object bean);
    }

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