Spring源码学习--从Springboot的ApplicationContext获取Bean

某些类A无法注入的情况下,需要用到其他被Spring注入的对象B,此时在A类如果想使用B,可以采取下面的方式

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

/** * Description:获取bean工具 * * @author DemoTransfer * @date 2018年5月19日 下午1:42:56 */
public class SpringBeanUtil {

    private static ApplicationContext applicationContext;
    static final private Object lock = new Object();

    /** * 设置上下文 * * @param applicationContext * @throws BeansException */
    public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        synchronized (lock) {
            if (SpringBeanUtil.applicationContext == null) {
                SpringBeanUtil.applicationContext = applicationContext;
            }
        }
    }

    /** * 获取applicationContext * * @return */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /** * 通过name获取 Bean * * @param name * @return */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /** * 通过class获取Bean * * @param clazz * @return */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /** * 通过name,以及Clazz返回指定的Bean * * @param name * @param clazz * @return */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

设置ApplicationContext地方

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class WebApplication {

    private static ApplicationContext applicationContext;

    public static void main(String[] args) {
        applicationContext = SpringApplication.run(WebApplication.class, args);
        SpringBeanUtil.setApplicationContext(applicationContext);
    }

}

使用场景

UnInstallServiceImpl unInstallServiceImpl = (UnInstallServiceImpl) SpringBeanUtil.getBean("unInstallService");
    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/u013412772/article/details/80376709
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞