实现ApplicationContextAware得到自己的bean工具

Posted imjamin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了实现ApplicationContextAware得到自己的bean工具相关的知识,希望对你有一定的参考价值。

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!");
        }
    }

}

在使用的时候 SpringContextHolder.getBean(MembersService.class)得到spring托管的bean

以上是关于实现ApplicationContextAware得到自己的bean工具的主要内容,如果未能解决你的问题,请参考以下文章

实现ApplicationContextAware接口时,获取ApplicationContext为null

通过实现ApplicationContextAware接口动态获取bean

ApplicationContextAware接口实现多继承Bean装配

在spring项目中,普通类注入获取Bean,实现ApplicationContextAware接口

ApplicationContextAware 的 setApplicationContext() 方法执行逻辑全解析

ApplicationContextAware 接口