持有spring上下文的工具类

package com.muxue.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 持有spring上下文的工具类,一个系统只有一个SpringContextHolder
 * <p>该工具类主要用于:通过spring上下文获取bean</p>
 */
@Component
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        if(applicationContext!=null) throw new IllegalStateException("applicationContext 上下文已存在");
        System.out.println("spring注入上下文");
        applicationContext=context;
    }

    private static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    /**
     * 本类SpringContextHolder 被销毁时,将spring上下文置空
     * @throws Exception
     */
    @Override
    public void destroy() throws Exception {
        applicationContext=null;
    }

    /**
     * 根据类型获取ioc容器中的bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }
    /**
     * 根据beanName获取bean
     * @param beanName
     * @return
     */
    public static <T> T  getBean(String beanName) {
        return (T)getApplicationContext().getBean(beanName);

    }
}

当一个类实现了ApplicationContextAware之后,这个类就可以方便获得ApplicationContext中的所有bean,这个类可以直接获取spring配置文件中,所有有引用到的bean对象。

原理

setApplicationContext是Spring框架预留的一个关键的钩子方法,spring详细加载全过程如下:

  1. 调用 BeanNameAware 的 setBeanName 方法
  2. 调用 BeanFactoryAware 的 setBeanFactory 方法
  3. 调用 ApplicationContextAware 的 setApplicationContext
  4. 调用 InitializingBean 的 afterPropertiesSet 或者没有实现这个接口,但指定了@Bean(initMethod="不加括号的方法名"),会执行这个方法
  5. 调用 BeanPostProcessor 的 postProcessBeforeInitialization 方法
  6. 调用 BeanPostProcessor 的 postProcessAfterInitialization 方法
  7. Bean 初始化完成,可以被使用
  8. 容器关闭前,调用 DisposableBean 的 destroy 方法

加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的setApplicationContext,自动的将ApplicationContext注入进来。

在ApplicationContextAware的实现类中,就可以通过这个上下文环境对象得到Spring容器中的Bean。

猜你喜欢

转载自blog.csdn.net/puzi0315/article/details/130238455
今日推荐