美文网首页
实现容器工具类,及其原理

实现容器工具类,及其原理

作者: guessguess | 来源:发表于2020-06-29 21:19 被阅读0次

首先想到第一种方式,但是这种做法有一个坏处,就是所有用到的类,都必须依赖这个工具类,那么问题来了,有没有一种好一点的做法呢?

@Component
public class ApplicationContextUtils implements ApplicationContextAware{
    private ApplicationContext context;
    public <T> T getBean(Class<T> t) {
        return context.getBean(t);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}

稍微调整一下代码,加一个静态变量即可,这样子我们就可以通过ApplicationContextUtils.APP_CONTEXT来做许多事情了

@Component
public class ApplicationContextUtils implements ApplicationContextAware{
    private ApplicationContext context;
    public static ApplicationContext APP_CONTEXT;
    public <T> T getBean(Class<T> t) {
        return context.getBean(t);
    }
    
    public String[] getBeanNames() {
        return context.getBeanDefinitionNames();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
        APP_CONTEXT = applicationContext;
    }
}

还有另外一种操作也是可行的,就是通过bean的后置处理器。但是显得有点多此一举。不过还是先贴代码。有点像脱裤子放屁....

@Component
public class ApplicationContextUtils implements ApplicationContextAware{
    private ApplicationContext context;
    public static ApplicationContext APP_CONTEXT;
    public <T> T getBean(Class<T> t) {
        return context.getBean(t);
    }
    
    public String[] getBeanNames() {
        return context.getBeanDefinitionNames();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
        //APP_CONTEXT = applicationContext;
    }

    public ApplicationContext getContext() {
        return context;
    }

    public static String getActiveProfile() {
        return STATIC_APPLICATION_CONTEXT.getEnvironment().getActiveProfiles()[0];
    }
}

@Component
public class CustomeBeanPostProcessor implements BeanPostProcessor{
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof ApplicationContextUtils) {
            ApplicationContextUtils appContextUtilsInstance = (ApplicationContextUtils)bean;
            appContextUtilsInstance.APP_CONTEXT = appContextUtilsInstance.getContext();
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}

先来说说为什么ApplicationContextAware这个接口,同时将bean交给spring管理就可以获得容器实例本身。以上那些bean都放在配置类的包或者子包下就可以了。

先贴上配置类

@SpringBootApplication
@EnableAspectJAutoProxy
@ServletComponentScan
public class Config {
    public static void main(String args[]) {
        SpringApplication.run(Config.class, args);
    }
}

pom文件

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gee</groupId>
    <artifactId>sb-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 开启热部署 -->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- 监控 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- json -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>

        <!-- 单元测试 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- 指定maven编译的jdk的版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <!-- 打包成springboot专用的jar包,指定入口信息等等 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

直接启动main方法,进行debug,看看debug的路径图


image.png

从路径上来看,其实ApplicationContextUtils的ApplicationContext变量是在ApplicationContextUtils实例化的时候完成的。
那么下面来看看代码吧

1.容器刷新

public class SpringApplication {
    public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
        configureHeadlessProperty();
        SpringApplicationRunListeners listeners = getRunListeners(args);
        listeners.starting();
        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                    args);
            ConfigurableEnvironment environment = prepareEnvironment(listeners,
                    applicationArguments);
            configureIgnoreBeanInfo(environment);
            Banner printedBanner = printBanner(environment);
            //先创建容器
            context = createApplicationContext();
            exceptionReporters = getSpringFactoriesInstances(
                    SpringBootExceptionReporter.class,
                    new Class[] { ConfigurableApplicationContext.class }, context);
            prepareContext(context, environment, listeners, applicationArguments,
                    printedBanner);
            //随后刷新,那么如何刷新的呢...一直往上走,其实最后是父类AbstractApplicationContext的refresh方法
            refreshContext(context);
            afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                new StartupInfoLogger(this.mainApplicationClass)
                        .logStarted(getApplicationLog(), stopWatch);
            }
            listeners.started(context);
            callRunners(context, applicationArguments);
        }
        catch (Throwable ex) {
            handleRunFailure(context, listeners, exceptionReporters, ex);
            throw new IllegalStateException(ex);
        }
        listeners.running(context);
        return context;
    }
}

//这个类其实是一个很重要的类,容器的大多数方法都在这个类实现的。看注释就好了,会说明哪里是重点。

public abstract class AbstractApplicationContext extends DefaultResourceLoader
        implements ConfigurableApplicationContext {
    @Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // 容器刷新前的准备,修改容器的状态...
            prepareRefresh();

            // 获取beanFactory
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // bean工厂的前置准备
            prepareBeanFactory(beanFactory);

            try {
                // 其实是一个暴露给子类去对beanFactory进行操作的方法
                postProcessBeanFactory(beanFactory);

                // beanFactoryPostProcessor以及beanDefinitionRegistryPostProcessor后置处理器的执行
                //这里主要涉及到的就是ConfigurationClassPostProcessor,会将配置类包路径下被@component标记的类以及通过@Import导入的类,进行注册。同时beanFactory和beanDefinitionRegistry的后置处理器也会进行实例化,并且执行。beanFactory的后置处理器,比如ServletComponentRegistryBeanFactoryPostProcessor会根据@ServletComponent指定的包,扫描对应的servlet组件,并且注入容器。
                invokeBeanFactoryPostProcessors(beanFactory);

                // 注册同时实例化bean的后置处理器。
                registerBeanPostProcessors(beanFactory);

                //初始化信息源
                initMessageSource();

                initApplicationEventMulticaster();

                // 给子类提供修改刷新方法的入口
                onRefresh();

                // 扫描以及注册监听器
                registerListeners();

                //初始化注册表中所有的类,放入singleObjects的缓存中(内置的后置处理器以及自定义的后置,以及内部类已经实例化了,剩下的只有一些用户自定义的类,这个方法才是核心。直接往里面走吧。
                finishBeanFactoryInitialization(beanFactory);

                // 完成刷新
                finishRefresh();
            }

            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }

}

一路debug,最后到这个方法,其实这个方法是实例化的入口。

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
        implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    
    @Override
    public void preInstantiateSingletons() throws BeansException {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Pre-instantiating singletons in " + this);
        }

        // 注册表中的bean的名字
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

        // 实例化所有非懒加载的bean
        for (String beanName : beanNames) {
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                //如果是factoryBean,则试图去getBean
                if (isFactoryBean(beanName)) {
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                    if (bean instanceof FactoryBean) {
                        final FactoryBean<?> factory = (FactoryBean<?>) bean;
                        boolean isEagerInit;
                        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                            isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                            ((SmartFactoryBean<?>) factory)::isEagerInit,
                                    getAccessControlContext());
                        }
                        else {
                            isEagerInit = (factory instanceof SmartFactoryBean &&
                                    ((SmartFactoryBean<?>) factory).isEagerInit());
                        }
                        if (isEagerInit) {
                            getBean(beanName);
                        }
                    }
                }
                else {
                    //若不是factoryBean,就直接获取,那么直接看getBean方法就好了,这个方法涉及到bean的创建。
                    getBean(beanName);
                }
            }
        }

        //。。。下面的代码不重要,直接忽略了。
    }
}

一路debug,来到了AbstractBeanFactory的doGetBean方法,这里才是真正创建bean的入口,方法有点长,注意看注释哈

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    @SuppressWarnings("unchecked")
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
        //转换一下bean的名字
        final String beanName = transformedBeanName(name);
        Object bean;

        // 这里其实是优先从缓存中获取bean实例
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isDebugEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            //若缓存存在,则会根据类型最后返回实例,factoryBean需要特殊处理,通过getObject
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
            //若缓存中不存在,则会判断是不是多例,多例不允许循环依赖,有一个threadLoacl的变量用于缓存正在创建中的bean
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            // 从父容器中获取bean
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
            }

            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }

            try {
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                //强依赖bean的注册以及实例化,同样不支持循环依赖
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dep : dependsOn) {
                        if (isDependent(beanName, dep)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                        }
                        registerDependentBean(dep, beanName);
                        getBean(dep);
                    }
                }

                // 创建实例,此处是重点,getSingleton方法其实是将bean最后放入一级缓存中,所以我们这里需要真正关心的是createBean方法。直接看看createBean方法的内部实现。
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {
                            destroySingleton(beanName);
                            throw ex;
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                else if (mbd.isPrototype()) {
                    //多态则直接createBean即可
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                        afterPrototypeCreation(beanName);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                else {
                    //其他域的bean的创建,如request,session,此处略过
                    String scopeName = mbd.getScope();
                    final Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, () -> {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            }
                            finally {
                                afterPrototypeCreation(beanName);
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {
                        throw new BeanCreationException(beanName,
                                "Scope '" + scopeName + "' is not active for the current thread; consider " +
                                "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                ex);
                    }
                }
            }
            catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

        // Check if required type matches the type of the actual bean instance.
        if (requiredType != null && !requiredType.isInstance(bean)) {
            try {
                T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
                if (convertedBean == null) {
                    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
                }
                return convertedBean;
            }
            catch (TypeMismatchException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to convert bean '" + name + "' to required type '" +
                            ClassUtils.getQualifiedName(requiredType) + "'", ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }
}

createBean方法的内部实现

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
        implements AutowireCapableBeanFactory {
    @Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        if (logger.isDebugEnabled()) {
            logger.debug("Creating instance of bean '" + beanName + "'");
        }
        RootBeanDefinition mbdToUse = mbd;

        // Make sure bean class is actually resolved at this point, and
        // clone the bean definition in case of a dynamically resolved Class
        // which cannot be stored in the shared merged bean definition.
        Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        // Prepare method overrides.
        try {
            mbdToUse.prepareMethodOverrides();
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                    beanName, "Validation of method overrides failed", ex);
        }

        try {
            //此处其实是给用户一个机会自己去返回实例,实现InstantiationAwareBeanPostProcessor接口即可并且注入容器即可,此处不是重点
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {
                return bean;
            }
        }
        catch (Throwable ex) {
            throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                    "BeanPostProcessor before instantiation of bean failed", ex);
        }

        try {
            //创建bean的核心。直接往里面走。
            Object beanInstance = doCreateBean(beanName, mbdToUse, args);
            if (logger.isDebugEnabled()) {
                logger.debug("Finished creating instance of bean '" + beanName + "'");
            }
            return beanInstance;
        }
        。。。下面还有部分catch的代码直接忽略
    }


    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
            throws BeanCreationException {

        // 实例化bean
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            //试图从factoryBean中获取缓存实例
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        if (instanceWrapper == null) {
            //没有缓存,直接创建,同时包装成instanceWrapper,这里是通过反射创建bean实例
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        //获取实例
        final Object bean = instanceWrapper.getWrappedInstance();
        Class<?> beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        // 允许后置处理器去重新整合beanDefinition
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    //这里面其实也是责任链模式,其中比较重要的一个后置处理器,AutowiredAnnotationPostProcessor会去生成该类的依赖元数据缓存,供后续解决依赖注入使用。
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Post-processing of merged bean definition failed", ex);
                }
                mbd.postProcessed = true;
            }
        }


        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isDebugEnabled()) {
                logger.debug("Eagerly caching bean '" + beanName +
                        "' to allow for resolving potential circular references");
            }
            //将实例对象加入三级缓存。spring一共有三级缓存,singletonFactories,earlySingletonObjects,singletonObjects只有singletonObjects才是完善后的实例缓存,且只会有任意一级缓存存在数据。为了解决循环依赖。
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // 初始化bean对象
        Object exposedObject = bean;
        try {
            //populate这里就是解决依赖注入的方法,利用提前生成的依赖元数据去对依赖的对象进行创建。
            //举个例子,a依赖b,b依赖a,a先创建之后,放入三级缓存,随后生成a的依赖元数据,去创建b,这个时候b去创建,生成b的依赖元数据,去创建a,发现可以从三级缓存中获取a,另外顺便将a从3级缓存移到2级缓存,此时b创建完成,a继续创建
            populateBean(beanName, mbd, instanceWrapper);
            //此处是重点,包括aop生成的代理对象,也是从此处返回,以及bean的后置处理器执行。直接往里面走。
            exposedObject = initializeBean(beanName, exposedObject, mbd);
        }
        catch (Throwable ex) {
            if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
                throw (BeanCreationException) ex;
            }
            else {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
            }
        }

        if (earlySingletonExposure) {
            //看看1/2级缓存中是否存在数据,若有则优先用
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                //如果使用了动态代理,那么优先使用动态代理生成的实例
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                }
                else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                    for (String dependentBean : dependentBeans) {
                        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }
                    if (!actualDependentBeans.isEmpty()) {
                        throw new BeanCurrentlyInCreationException(beanName,
                                "Bean with name '" + beanName + "' has been injected into other beans [" +
                                StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                "] in its raw version as part of a circular reference, but has eventually been " +
                                "wrapped. This means that said other beans do not use the final version of the " +
                                "bean. This is often the result of over-eager type matching - consider using " +
                                "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

        // Register bean as disposable.
        try {
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        }
        catch (BeanDefinitionValidationException ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
        }

        return exposedObject;
    }

    //如何初始化bean呢?操作只有初始化前,初始化后
    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 {
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
         //说明是可以修改的类型
        if (mbd == null || !mbd.isSynthetic()) {
            //看看初始化前有什么操作,直接进入
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
            //执行init方法
            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()) {
            //看看初始化后有什么操作,其实这里比较重要的是一个叫AbstractAutoProxyCreator的类,会去注册表中找出所有的切面类,找出每个切面类的增强方法,生成缓存,随后会判断类是否可以被增强,找出其对应的增强方法,同时进行排序,最后根据增强器的pointCut表达式来判断,动态代理的method是否符合,将增强方法进行织入,生成动态代理对象。而我们对这里做的操作仅仅是去操作自定义的bean罢了,看看代码。
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }

    //初始化前的后置处理
    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            //当执行到ApplicationContextAwareProcessor的时候,直接进入其postProcessBeforeInitialization方法
            Object current = beanProcessor.postProcessBeforeInitialization(result, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }
}

ApplicationContextAwareProcessor如何将容器注入到用户提供的类中呢,看到这里一目了然了

class ApplicationContextAwareProcessor implements BeanPostProcessor {
    @Override
    @Nullable
    public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
        AccessControlContext acc = null;

        if (System.getSecurityManager() != null &&
                (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
                        bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
                        bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
            acc = this.applicationContext.getBeanFactory().getAccessControlContext();
        }

        if (acc != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                invokeAwareInterfaces(bean);
                return null;
            }, acc);
        }
        else {
            invokeAwareInterfaces(bean);
        }

        return bean;
    }

    private void invokeAwareInterfaces(Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof EnvironmentAware) {
                ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
            }
            if (bean instanceof EmbeddedValueResolverAware) {
                ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
            }
            if (bean instanceof ResourceLoaderAware) {
                ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
            }
            if (bean instanceof ApplicationEventPublisherAware) {
                ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
            }
            if (bean instanceof MessageSourceAware) {
                ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
            }
            //所以必须提供一个set方法,就是实现ApplicationContextAware接口就好了,这样子在创建bean的时候,就可以设置容器了。
            if (bean instanceof ApplicationContextAware) {
                ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
            }
        }
    }
}

文中的第二种脱裤子放屁的办法就是bean的后置处理器的执行

class ApplicationContextAwareProcessor implements BeanPostProcessor {

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
            //执行到CustomeBeanPostProcessor的时候,就会进入到里面的方法。
            Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }
}

@Component
public class CustomeBeanPostProcessor implements BeanPostProcessor{
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof ApplicationContextUtils) {
            ApplicationContextUtils appContextUtilsInstance = (ApplicationContextUtils)bean;
            appContextUtilsInstance.APP_CONTEXT = appContextUtilsInstance.getContext();
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}

相关文章

  • 实现容器工具类,及其原理

    首先想到第一种方式,但是这种做法有一个坏处,就是所有用到的类,都必须依赖这个工具类,那么问题来了,有没有一种好一点...

  • SKIL/安装/Kubernetes

    Kubernetes Kubernetes是一个用于容器编排的开源工具。它在管理容器工作负载和实现集群及其部署的自...

  • SparseArray原理分析

    系列文章地址:Android容器类-ArraySet原理解析(一)Android容器类-ArrayMap原理解析(...

  • SparseIntArray原理分析

    系列文章地址:Android容器类-ArraySet原理解析(一)Android容器类-ArrayMap原理解析(...

  • Servlet与Jsp(1)

    Servlet 实现原理Servlet接口使Servlet容器能将Servlet类载入内存,并在Servlet实例...

  • Java容器类概览

    Java提供的容器类是我们最常用的工具类,List,Set,Map等容器在我们的项目中无处不在。了解了容器的实现原...

  • ThreadLocal(二)

    实现原理ThreadLocal可以看做是一个容器,容器里面存放着属于当前线程的变量。ThreadLocal类提供了...

  • 关于Java中集合ArrayList、LinkedList以及H

    前言Java中容器对象主要用来存储其他对象,根据实现原理不同,主要有3类常用的容器对象: 1、ArrayList ...

  • SpringBoot之@Import注解(Registrar使用

    目标 仿照OpenFegin向SpringIOC容器中添加一些服务类或工具,这里我们需要实现 实现 创建全局注解@...

  • 技术点

    1Java集合主要是hashmap实现原理2.多线程问AQS源码、并发工具类源码、锁的实现原理、阻塞队列源码、线程...

网友评论

      本文标题:实现容器工具类,及其原理

      本文链接:https://www.haomeiwen.com/subject/dpdafktx.html