zoukankan      html  css  js  c++  java
  • Spring中为什么继承了ApplicationContextAware接口就可以使用ApplicationContext对象?

    1Spring中使用applicationContext对象

    public class SpringContextUtil implements ApplicationContextAware
    {
        private static ApplicationContext applicationContext;
     
        @Override
        public void setApplicationContext(ApplicationContext applicationContext)
        {
            applicationContext = applicationContext;
        }
    
        public static ApplicationContext getApplicationContext()
        {
            return applicationContext;
        }
    }

    2、为什么继承ApplicationContextAware就可以使用applicationContext对象?

         使用后置处理器

    3、什么是后置处理器?
          后置处理器主要是对bean进行增强,包括在bean初始化前和初始化后进行增强,如修改bean属性、对bean的方法进行代理等。

    public interface BeanPostProcessor {
         // bean初始化前增强
        default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }
    // bean初始化后增强
        default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }

    4、后置处理器怎样调用setApplicationContext赋值

         内置后置处理器:org.springframework.context.support.ApplicationContextAwareProcessor

    class  ApplicationContextAwareProcessor implements BeanPostProcessor 
    
    public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
        
            else {
                invokeAwareInterfaces(bean);
            }
    
            return bean;
        }
    
    private void invokeAwareInterfaces(Object bean) {
            if (bean instanceof Aware) {
                // 对继承于ApplicationContextAware的bean调用setApplicationContext方法进行赋值
                if (bean instanceof ApplicationContextAware) {
                    ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
                }
            }
        }

    5、参考资料

        https://blog.csdn.net/baomw/article/details/84262006

  • 相关阅读:
    Python 一条语句如何在多行显示的问题
    代理模式
    MySQL workbench中的PK,NN,UQ,BIN,UN,ZF,AI说明
    异步加载 Echarts图的数据
    Web页面中两个listbox的option的转移
    半透明效果
    在地图上使图片透明
    加载图片方式
    获取鼠标坐标
    画笔与画刷
  • 原文地址:https://www.cnblogs.com/gossip/p/11694469.html
Copyright © 2011-2022 走看看