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

  • 相关阅读:
    redis数据结构
    django内置密码原理
    生成图片验证码
    如何封装VUE的axios请求
    杭电1717小数化分数2
    杭电2504 又见GCD
    杭电 2136 Largest prime factor(最大素数因子的位置)
    Linux终端的一些快捷键命令
    杭电 1772 cake
    杭电ACM 1713 相遇周期
  • 原文地址:https://www.cnblogs.com/gossip/p/11694469.html
Copyright © 2011-2022 走看看