深入Spring:自定義IOC

前言

上一篇文章講了如何自定義注解耍共,注解的加載和使用苗傅,這篇講一下Spring的IOC過程滑潘,并通過自定義注解來實現(xiàn)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;
    }

}

運行代碼就會發(fā)現(xiàn)被@MyInject修飾的fieldClass被注入進去了霜威。這個功能是借用了Spring內置的AutowiredAnnotationBeanPostProcessor類來實現(xiàn)的谈喳。
Spring的IOC主要是通過@Resource@Autowired@Inject等注解來實現(xiàn)的戈泼,Spring會掃描Bean的類信息婿禽,讀取并設置帶有這些注解的屬性赏僧。查看Spring的源代碼,就會發(fā)現(xiàn)其中@Resource是由CommonAnnotationBeanPostProcessor解析并注入的扭倾。具體的邏輯是嵌入在代碼中的淀零,沒法進行定制。
@Autowired膛壹,@Inject是由AutowiredAnnotationBeanPostProcessor解析并注入,觀察這個類就會發(fā)現(xiàn)驾中,解析注解是放在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);
    }

同時,這個類實現(xiàn)了InstantiationAwareBeanPostProcessor接口链方,Spring會在初始化Bean的時候查找實現(xiàn)InstantiationAwareBeanPostProcessor的Bean持痰,并調用接口定義的方法,具體實現(xiàn)的邏輯在AbstractAutowireCapableBeanFactorypopulateBean方法中。
AutowiredAnnotationBeanPostProcessor實現(xiàn)了這個接口的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是利用特定的接口來實現(xiàn)依賴注入的。所以自定義的注解注入薪者,也可以通過實現(xiàn)相應的接口來嵌入到Bean的初始化過程中纵苛。

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

第二個例子就是實現(xiàn)BeanPostProcessor接口,嵌入到Bean的初始化過程中言津,來完成自定義注入的攻人,完整的例子同樣放在Github,第二個例子實現(xiàn)了兩種注入模式悬槽,第一種是單個字段的注入怀吻,用@MyInject注解字段。第二種是使用@FullInject注解初婆,會掃描整理類的所有字段蓬坡,進行注入。這里主要說明一下@FullInject的實現(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的實現(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實例化完成,初始化之前調用的弊琴。這里查找類帶有的注解信息兆龙,如果帶有@FullInject,就查找類的所有字段敲董,并從applicationContext取出對應的bean注入到這些字段中紫皇。

結語

Spring提供了很多接口來實現(xiàn)自定義功能慰安,就像這兩篇用到的BeanFactoryPostProcessorBeanPostProcessor,這兩個主要是嵌入到BeanFactory和Bean的構造過程中坝橡,他們的子類還會有更多更精細的控制泻帮。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市计寇,隨后出現(xiàn)的幾起案子锣杂,更是在濱河造成了極大的恐慌,老刑警劉巖番宁,帶你破解...
    沈念sama閱讀 216,744評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件元莫,死亡現(xiàn)場離奇詭異,居然都是意外死亡蝶押,警方通過查閱死者的電腦和手機踱蠢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,505評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來棋电,“玉大人茎截,你說我怎么就攤上這事「峡” “怎么了企锌?”我有些...
    開封第一講書人閱讀 163,105評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長于未。 經常有香客問我撕攒,道長,這世上最難降的妖魔是什么烘浦? 我笑而不...
    開封第一講書人閱讀 58,242評論 1 292
  • 正文 為了忘掉前任抖坪,我火速辦了婚禮,結果婚禮上闷叉,老公的妹妹穿的比我還像新娘擦俐。我一直安慰自己,他們只是感情好握侧,可當我...
    茶點故事閱讀 67,269評論 6 389
  • 文/花漫 我一把揭開白布捌肴。 她就那樣靜靜地躺著,像睡著了一般藕咏。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上秽五,一...
    開封第一講書人閱讀 51,215評論 1 299
  • 那天孽查,我揣著相機與錄音,去河邊找鬼坦喘。 笑死盲再,一個胖子當著我的面吹牛西设,可吹牛的內容都是我干的。 我是一名探鬼主播答朋,決...
    沈念sama閱讀 40,096評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼贷揽,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了梦碗?” 一聲冷哼從身側響起禽绪,我...
    開封第一講書人閱讀 38,939評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎洪规,沒想到半個月后印屁,有當地人在樹林里發(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 45,354評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡斩例,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,573評論 2 333
  • 正文 我和宋清朗相戀三年雄人,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片念赶。...
    茶點故事閱讀 39,745評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡础钠,死狀恐怖,靈堂內的尸體忽然破棺而出叉谜,到底是詐尸還是另有隱情旗吁,我是刑警寧澤,帶...
    沈念sama閱讀 35,448評論 5 344
  • 正文 年R本政府宣布正罢,位于F島的核電站阵漏,受9級特大地震影響,放射性物質發(fā)生泄漏翻具。R本人自食惡果不足惜履怯,卻給世界環(huán)境...
    茶點故事閱讀 41,048評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望裆泳。 院中可真熱鬧叹洲,春花似錦、人聲如沸工禾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,683評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽闻葵。三九已至民泵,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間槽畔,已是汗流浹背栈妆。 一陣腳步聲響...
    開封第一講書人閱讀 32,838評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人鳞尔。 一個月前我還...
    沈念sama閱讀 47,776評論 2 369
  • 正文 我出身青樓嬉橙,卻偏偏與公主長得像,于是被迫代替她去往敵國和親寥假。 傳聞我的和親對象是個殘疾皇子市框,可洞房花燭夜當晚...
    茶點故事閱讀 44,652評論 2 354

推薦閱讀更多精彩內容