14、web项目获取Spring的上下文环境ApplicationContext

推荐学习:
https://blog.csdn.net/yang123111/article/details/32099329

在web项目中,spring上下文由容器初始化,所以此时想要获取ApplicationContext,不能再new,否则会重复初始化,需要用如下方法:

@Component
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext; // Spring应用上下文环境
    /*
     * 
     * 实现了ApplicationContextAware 接口,必须实现该方法;
     * 通过传递applicationContext参数初始化成员变量applicationContext
     */
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }
}

使用时使用@Autowired注入到自己的service中,
springContextUtil.getBean(beanName);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,014评论 19 139
  • 我在这里, 你在哪里? 好像迷失在人群中,好像一下子忘记了我是谁, 好像一瞬间遗失了什么重要的记忆, 人群中有一个...
    思沐ls阅读 137评论 0 0
  • 你不必扫码加入“父母学院”, 因为你没有时间学习如何做一个好父母, 孩子就出世了。 你不必扫码加入“管理学院”, ...
    水歌传媒阅读 297评论 0 1