前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >监听器获取spring配置文件创建的对象

监听器获取spring配置文件创建的对象

作者头像
爱撒谎的男孩
发布2019-12-31 15:03:41
9690
发布2019-12-31 15:03:41
举报
文章被收录于专栏:码猿技术专栏码猿技术专栏

文章目录

  1. 1. 监听器获取spring配置文件创建的对象
    1. 1.1. 前提
    2. 1.2. 准备
    3. 1.3. 实现
    4. 1.4. 参考文章

监听器获取spring配置文件创建的对象

前提

  • 我们在使用监听器的时候,会用到spring配置文件创建的对象,那么我们不能像其他的类中直接使用@Resource或者@AutoWired自动注入对象,那么我们如何获取对象呢
  • 比如我们在缓存数据的时候,就是在容器启动的时候读取数据库中的信息缓存在ServletContext中,那么我们肯定需要调用Service中的对象来获取数据库中的信息,此时我们就需要获取spring配置文件配置的业务层的对象

准备

  • 前提是你的spring的配置文件是使用的spring监听器ContextLoaderListener加载的,而不是一起在springMVC的前端控制器中加载,比如你在web.xml配置如下
代码语言:javascript
复制
<!--配置spring配置问文件的路径-->
<context-param>
		<param-name>contextConfigLocation</param-name>
    	<!--使用通配符指定多个配置文件,比如 spring-service.xml,spring-dao.xml-->
		<param-value>classpath:spring-*.xml</param-value>
	</context-param>
	<!--spring监听器-->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

实现

  • 我们先创建一个ServletContext上下文监听器,在其中使用WebApplicationContextUtils类获取WebApplicationContext对象,之后即可获取其中spring创建的bean
代码语言:javascript
复制
public class InitCompontServletContextListener implements ServletContextListener, ServletContextAttributeListener {
	
	private BlogIndex blogIndex;    //spring配置创建的对象
	private IBlogService blogService;   //spring配置创建的对象

	/**
     * web容器初始化的时候就会调用
     */
    public void contextInitialized(ServletContextEvent contextEvent)  {
    	ServletContext context=contextEvent.getServletContext();  //获取上下文对象
    	WebApplicationContext applicationContext=WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    	blogIndex=applicationContext.getBean("blogIndex",BlogIndex.class);  //加载BlogIndex对象
    	blogService=applicationContext.getBean("blogServiceImpl",IBlogService.class);  //加载IBlogService对象
    }

参考文章

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 监听器获取spring配置文件创建的对象
    • 前提
      • 准备
        • 实现
          • 参考文章
          相关产品与服务
          容器服务
          腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档