SpringBoot中注入ApplicationContext对象的三种方式

【本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

在项目中,我们可能需要手动获取spring中的bean对象,这时就需要通过 ApplicationContext 去操作一波了!

1、直接注入(Autowired)

@Component
public class User {

    @Autowired
    private ApplicationContext applicationContext;
}

2、构造器方法注入

@Component
public class User{
    private ApplicationContext applicationContext;

    public User(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}

3、手动构建类实现接口

/**
 * Spring的ApplicationContext的持有者,可以用静态方法的方式获取spring容器中的bean
 *
 * @date 2018年5月27日 下午6:32:11
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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

    public static ApplicationContext getApplicationContext() {
        assertApplicationContext();
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        assertApplicationContext();
        return (T) applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> requiredType) {
        assertApplicationContext();
        return applicationContext.getBean(requiredType);
    }

    private static void assertApplicationContext() {
        if (SpringContextHolder.applicationContext == null) {
            throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
        }
    }

}

可以在使用类上添加 @DependsOn(“springContextHolder”),确保在此之前 SpringContextHolder 类已加载!

本文转载自:https://blog.csdn.net/Abysscarry/article/details/80490624

版权声明

【本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

原文地址:https://www.cnblogs.com/onblog/p/13050368.html