深入Spring:自定义IOC

前言

上一篇文章讲了如何自定义注解,注解的加载和使用,这篇讲一下Spring的IOC过程,并通过自定义注解来实现IOC。

自定义注解

还是先看一下个最简单的例子,源码同样放在了Github
先定义自己的注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyInject {
}

注入AutowiredAnnotationBeanPostProcessor,并设置自己定义的注解类

@Configuration
public class CustomizeAutowiredTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(CustomizeAutowiredTest.class);
        annotationConfigApplicationContext.refresh();
        BeanClass beanClass = annotationConfigApplicationContext.getBean(BeanClass.class);
        beanClass.print();
    }
    @Component
    public static class BeanClass {
        @MyInject
        private FieldClass fieldClass;
        public void print() {
            fieldClass.print();
        }
    }
    @Component
    public static class FieldClass {
        public void print() {
            System.out.println("hello world");
        }
    }
    @Bean
    public AutowiredAnnotationBeanPostProcessor getAutowiredAnnotationBeanPostProcessor() {
        AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
        autowiredAnnotationBeanPostProcessor.setAutowiredAnnotationType(MyInject.class);
        return autowiredAnnotationBeanPostProcessor;
    }

}

运行代码就会发现被@MyInject修饰的fieldClass被注入进去了。这个功能是借用了Spring内置的AutowiredAnnotationBeanPostProcessor类来实现的。
Spring的IOC主要是通过@Resource@Autowired@Inject等注解来实现的,Spring会扫描Bean的类信息,读取并设置带有这些注解的属性。查看Spring的源代码,就会发现其中@Resource是由CommonAnnotationBeanPostProcessor解析并注入的。具体的逻辑是嵌入在代码中的,没法进行定制。
@Autowired@Inject是由AutowiredAnnotationBeanPostProcessor解析并注入,观察这个类就会发现,解析注解是放在autowiredAnnotationTypes里面的,所以初始化完成后,调用setAutowiredAnnotationType(MyInject.class) 设置自定义的注解。

    public AutowiredAnnotationBeanPostProcessor() {
        this.autowiredAnnotationTypes.add(Autowired.class);
        this.autowiredAnnotationTypes.add(Value.class);
        try {
            this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
                    ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
            logger.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
        }
        catch (ClassNotFoundException ex) {
            // JSR-330 API not available - simply skip.
        }
    }
    public void setAutowiredAnnotationType(Class<? extends Annotation> autowiredAnnotationType) {
        Assert.notNull(autowiredAnnotationType, "'autowiredAnnotationType' must not be null");
        this.autowiredAnnotationTypes.clear();
        this.autowiredAnnotationTypes.add(autowiredAnnotationType);
    }

同时,这个类实现了InstantiationAwareBeanPostProcessor接口,Spring会在初始化Bean的时候查找实现InstantiationAwareBeanPostProcessor的Bean,并调用接口定义的方法,具体实现的逻辑在AbstractAutowireCapableBeanFactorypopulateBean方法中。
AutowiredAnnotationBeanPostProcessor实现了这个接口的postProcessPropertyValues方法。这个方法里,扫描了带有注解的字段和方法,并注入到Bean。

    public PropertyValues postProcessPropertyValues(
            PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass());
        try {
            metadata.inject(bean, beanName, pvs);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
        }
        return pvs;
    }

扫描的方法如下

    private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
        LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
        Class<?> targetClass = clazz;
        do {
            LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
            for (Field field : targetClass.getDeclaredFields()) {
                Annotation annotation = findAutowiredAnnotation(field);
                if (annotation != null) {
                    if (Modifier.isStatic(field.getModifiers())) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Autowired annotation is not supported on static fields: " + field);
                        }
                        continue;
                    }
                    boolean required = determineRequiredStatus(annotation);
                    currElements.add(new AutowiredFieldElement(field, required));
                }
            }
            for (Method method : targetClass.getDeclaredMethods()) {
                Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
                Annotation annotation = BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod) ?
                        findAutowiredAnnotation(bridgedMethod) : findAutowiredAnnotation(method);
                if (annotation != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Autowired annotation is not supported on static methods: " + method);
                        }
                        continue;
                    }
                    if (method.getParameterTypes().length == 0) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Autowired annotation should be used on methods with actual parameters: " + method);
                        }
                    }
                    boolean required = determineRequiredStatus(annotation);
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);
                    currElements.add(new AutowiredMethodElement(method, required, pd));
                }
            }
            elements.addAll(0, currElements);
            targetClass = targetClass.getSuperclass();
        }
        while (targetClass != null && targetClass != Object.class);
        return new InjectionMetadata(clazz, elements);
    }

注入的方法在AutowiredMethodElementAutowiredFieldElementinject()方法中。

自定义注解注入

AutowiredAnnotationBeanPostProcessor是利用特定的接口来实现依赖注入的。所以自定义的注解注入,也可以通过实现相应的接口来嵌入到Bean的初始化过程中。

  1. BeanPostProcessor会嵌入到Bean的初始化前后
  2. InstantiationAwareBeanPostProcessor继承自BeanPostProcessor,增加了实例化前后等方法

第二个例子就是实现BeanPostProcessor接口,嵌入到Bean的初始化过程中,来完成自定义注入的,完整的例子同样放在Github,第二个例子实现了两种注入模式,第一种是单个字段的注入,用@MyInject注解字段。第二种是使用@FullInject注解,会扫描整理类的所有字段,进行注入。这里主要说明一下@FullInject的实现方法。

  1. 定义FullInject
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FullInject {
}
  1. JavaBean
    public static class FullInjectSuperBeanClass {
        private FieldClass superFieldClass;
        public void superPrint() {
            superFieldClass.print();
        }
    }
    @Component
    @FullInject
    public static class FullInjectBeanClass extends FullInjectSuperBeanClass {
        private FieldClass fieldClass;
        public void print() {
            fieldClass.print();
        }
    }
  1. BeanPostProcessor的实现类
    @Component
    public static class MyInjectBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
        private ApplicationContext applicationContext;
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            if (hasAnnotation(bean.getClass().getAnnotations(), FullInject.class.getName())) {
                Class beanClass = bean.getClass();
                do {
                    Field[] fields = beanClass.getDeclaredFields();
                    for (Field field : fields) {
                        setField(bean, field);
                    }
                } while ((beanClass = beanClass.getSuperclass()) != null);
            } else {
                processMyInject(bean);
            }
            return bean;
        }
        private void processMyInject(Object bean) {
            Class beanClass = bean.getClass();
            do {
                Field[] fields = beanClass.getDeclaredFields();
                for (Field field : fields) {
                    if (!hasAnnotation(field.getAnnotations(), MyInject.class.getName())) {
                        continue;
                    }
                    setField(bean, field);
                }
            } while ((beanClass = beanClass.getSuperclass()) != null);
        }
        private void setField(Object bean, Field field) {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            try {
                field.set(bean, applicationContext.getBean(field.getType()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        private boolean hasAnnotation(Annotation[] annotations, String annotationName) {
            if (annotations == null) {
                return false;
            }
            for (Annotation annotation : annotations) {
                if (annotation.annotationType().getName().equals(annotationName)) {
                    return true;
                }
            }
            return false;
        }
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
    }
  1. main 方法
@Configuration
public class CustomizeInjectTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(CustomizeInjectTest.class);
        annotationConfigApplicationContext.refresh();
        FullInjectBeanClass fullInjectBeanClass = annotationConfigApplicationContext.getBean(FullInjectBeanClass.class);
        fullInjectBeanClass.print();
        fullInjectBeanClass.superPrint();
    }
}

这里把处理逻辑放在了postProcessBeforeInitialization方法中,是在Bean实例化完成,初始化之前调用的。这里查找类带有的注解信息,如果带有@FullInject,就查找类的所有字段,并从applicationContext取出对应的bean注入到这些字段中。

结语

Spring提供了很多接口来实现自定义功能,就像这两篇用到的BeanFactoryPostProcessorBeanPostProcessor,这两个主要是嵌入到BeanFactory和Bean的构造过程中,他们的子类还会有更多更精细的控制。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容