深入Spring:自定義IOC

前言

上一篇文章講了如何自定義注解,注解的加載和使用,這篇講一下Spring的IOC過程,并通過自定義注解來實(shí)現(xiàn)IOC。

自定義注解

還是先看一下個(gè)最簡單的例子,源碼同樣放在了Github
先定義自己的注解

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

注入AutowiredAnnotationBeanPostProcessor,并設(shè)置自己定義的注解類

@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;
    }

}

運(yùn)行代碼就會(huì)發(fā)現(xiàn)被@MyInject修飾的fieldClass被注入進(jìn)去了。這個(gè)功能是借用了Spring內(nèi)置的AutowiredAnnotationBeanPostProcessor類來實(shí)現(xiàn)的。
Spring的IOC主要是通過@Resource@Autowired@Inject等注解來實(shí)現(xiàn)的,Spring會(huì)掃描Bean的類信息,讀取并設(shè)置帶有這些注解的屬性。查看Spring的源代碼,就會(huì)發(fā)現(xiàn)其中@Resource是由CommonAnnotationBeanPostProcessor解析并注入的。具體的邏輯是嵌入在代碼中的,沒法進(jìn)行定制。
@Autowired@Inject是由AutowiredAnnotationBeanPostProcessor解析并注入,觀察這個(gè)類就會(huì)發(fā)現(xiàn),解析注解是放在autowiredAnnotationTypes里面的,所以初始化完成后,調(diào)用setAutowiredAnnotationType(MyInject.class) 設(shè)置自定義的注解。

    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);
    }

同時(shí),這個(gè)類實(shí)現(xiàn)了InstantiationAwareBeanPostProcessor接口,Spring會(huì)在初始化Bean的時(shí)候查找實(shí)現(xiàn)InstantiationAwareBeanPostProcessor的Bean,并調(diào)用接口定義的方法,具體實(shí)現(xiàn)的邏輯在AbstractAutowireCapableBeanFactorypopulateBean方法中。
AutowiredAnnotationBeanPostProcessor實(shí)現(xiàn)了這個(gè)接口的postProcessPropertyValues方法。這個(gè)方法里,掃描了帶有注解的字段和方法,并注入到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是利用特定的接口來實(shí)現(xiàn)依賴注入的。所以自定義的注解注入,也可以通過實(shí)現(xiàn)相應(yīng)的接口來嵌入到Bean的初始化過程中。

  1. BeanPostProcessor會(huì)嵌入到Bean的初始化前后
  2. InstantiationAwareBeanPostProcessor繼承自BeanPostProcessor,增加了實(shí)例化前后等方法

第二個(gè)例子就是實(shí)現(xiàn)BeanPostProcessor接口,嵌入到Bean的初始化過程中,來完成自定義注入的,完整的例子同樣放在Github,第二個(gè)例子實(shí)現(xiàn)了兩種注入模式,第一種是單個(gè)字段的注入,用@MyInject注解字段。第二種是使用@FullInject注解,會(huì)掃描整理類的所有字段,進(jìn)行注入。這里主要說明一下@FullInject的實(shí)現(xiàn)方法。

  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的實(shí)現(xiàn)類
    @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實(shí)例化完成,初始化之前調(diào)用的。這里查找類帶有的注解信息,如果帶有@FullInject,就查找類的所有字段,并從applicationContext取出對(duì)應(yīng)的bean注入到這些字段中。

結(jié)語

Spring提供了很多接口來實(shí)現(xiàn)自定義功能,就像這兩篇用到的BeanFactoryPostProcessorBeanPostProcessor,這兩個(gè)主要是嵌入到BeanFactory和Bean的構(gòu)造過程中,他們的子類還會(huì)有更多更精細(xì)的控制。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,024評(píng)論 3 413
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評(píng)論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,328評(píng)論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,878評(píng)論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評(píng)論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,098評(píng)論 0 286
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,616評(píng)論 1 331
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,554評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,725評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評(píng)論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 43,971評(píng)論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評(píng)論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,339評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,695評(píng)論 2 370

推薦閱讀更多精彩內(nèi)容