1. 程式人生 > >Spring原始碼解析—第六篇IOC之BeanFactoryAware

Spring原始碼解析—第六篇IOC之BeanFactoryAware

1、BeanFactoryAware簡介

實現這個介面的bean其實是希望知道自己屬於哪一個beanfactory

public interface BeanFactoryAware extends Aware {
    void setBeanFactory(BeanFactory beanFactory) throws BeansException;
}

2、例項

修改上面的例項,增加UserBeanFactoryAware

2.1、UserBeanFactoryAware類

public class UserBeanFactoryAware implements BeanFactoryAware {
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("I belong to :"+beanFactory);
    }
}

2.2、配置檔案增加

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user" class="com.vesus.spring.model.User" />
    <bean id="userbeanfactory" class="com.vesus.spring.factory.UserBeanFactoryAware"/>
</beans>

2.3、測試類

public class Test {
    public static void main(String[] args) {
        ApplicationContext context =  new ClassPathXmlApplicationContext("applicationContext.xml") ;
        UserBeanFactoryAware aware = (UserBeanFactoryAware) context.getBean("userbeanfactory");
    }
}

2.4、測試結果

I belong to :org.s
[email protected]
6bf256fa

3、原始碼分析

3.1、入口方法doGetBean()

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

        final String beanName = transformedBeanName(name);
        Object bean;

        ......

                //如果是單例
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            //建立bean
                            return createBean(beanName, mbd, args);
                        }
                    }
                }    
                        .....
        return (T) bean;
    }

繼續跟蹤得到BeanFactoryAware的呼叫方法initializeBean

3.2、initializeBean註冊方法解析

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                invokeAwareMethods(beanName, bean);
                return null;
            }, getAccessControlContext());
        }
        else {
            //判斷bean例項的型別,並執行相應的方法
            invokeAwareMethods(beanName, bean);
        }
        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            //在初始化之前處理執行處理器
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
            //開始執行初始化方法
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
            //在初始化之後處理執行處理器
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }

繼續跟蹤invokeAwareMethods可以看到BeanFactoryAware實現類的呼叫。

3.2、invokeAwareMethods方法解析

private void invokeAwareMethods(final String beanName, final Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ClassLoader bcl = getBeanClassLoader();
                if (bcl != null) {
                    ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
                }
            }
            //判斷是否為BeanFactoryAware例項,如果是,則呼叫setBeanFactory方法
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }

至此,BeanFactoryAware的原始碼分析完成。