介绍 1,在网络。xml中声明
这篇文章将为大家详细讲解有关利用弹簧怎么实现一个监听器功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
1,在网络。xml中声明
& lt; !——,自定义监听,启动加载系统参数,——比; ,& lt; listener> ,& lt; listener-class> com.cn.framework.constant.OmsConfigLoader & lt;/listener>
2,创建类OmsConfigLoader实现接口ServletContextListener,项目启动的时候服务还没有注入,此时调用服务的方法会报错,因为在web容器中无论是servlet还是滤波器都不是春容器来管理的。
侦听器的生命周期是web容器维护的,豆的生命周期是由春容器来维护的,所以在听众中使用@ resource,听众不认识,
可以沟通过如下方法来解决:
使用WebApplicationContextUtils工具类,该工具类的作用是获取到春容器的引用,进而获取到我们需要的bean实例。
package com.cn.framework.constant; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.log4j.Logger; import org.springframework.web.context.support.WebApplicationContextUtils; import com.kxs.service.systemService.ISystemService; public class  OmsConfigLoader implements ServletContextListener  { private static  Logger LOG =, Logger.getLogger (OmsConfigLoader.class); @Override public void  contextDestroyed (ServletContextEvent arg0), {//,TODO Auto-generated method 存根 } @Override public void  contextInitialized (ServletContextEvent arg0), { LOG.info(“==祝辞,加载OMS系统配置信息,Start ==?; try { ISystemService ISystemService =, WebApplicationContextUtils.getWebApplicationContext (arg0.getServletContext ()) .getBean (ISystemService.class); iSystemService.refreshCache (); },catch (Exception e), { e.printStackTrace (); LOG.info (e.toString ()); } LOG.info(“==祝辞,加载OMS系统配置信息,最终获得==?; } }
<>强补充:Spring xml配置自定义事件监听器强>
一、自定义事件
春天中使用自定义事件类型:
第一步:自定义事件类型:自定义类需要继承春天中org.springframework.context.ApplicationEvent类
第二步:设置事件监听器,实现org.springframework.context.ApplicationListener<自定义事件类型的在接口,重写onApplicationEvent方法监听事件源
第三步:将事件监听器配置到春天中,通过xml配置文件将事件监听器配置到bean容器中
第四步:春容器(集装箱容器发布事件)发布事件
<>强自定义事件类型强>
public class RainEvent extends ApplicationEvent { ,private static  final long  serialVersionUID =, 1 l; ,public RainEvent (Object 源),{ ,超级(源); }大敌; }
<>强监听器:可以创建多个监听器强>
public class RainEventListener1 implements ApplicationListener, { ,//监听rainevent事件,调用当前方法 ,@Override ,public void  onApplicationEvent (RainEvent 事件),{ ,Object source =, event.getSource (); ,System.out.println(“监听器1:“+源),, ,} } public class  RainEventListener2 implements ApplicationListener< RainEvent>, { ,//监听rainevent事件,调用当前方法 ,@Override ,public void  onApplicationEvent (RainEvent 事件),{ ,Object source =, event.getSource (); ,System.out.println(“监听器2:“+源),, ,} }
<强> xml配置文件将监听器配置到bean容器中强>
& lt; !——,配置监听器,向春容器发布事件,自动触发监听器的onApplicationEvent方法,——比; & lt; bean 类=癱om.briup.ioc.event.RainEventListener1"祝辞& lt;/bean> & lt; bean 类=癱om.briup.ioc.event.RainEventListener2"祝辞& lt;/bean>
<强>豆容器发布事件强>
public void ioc_event (), { ,try { String 才能;path =,“;com/briup/ioc/event/event.xml"; ApplicationContext 才能;container =, ,,,new ClassPathXmlApplicationContext(路径); ,,,, container.publishEvent才能(new RainEvent(“打雷了,下雨了!“)); ,}catch (Exception e), { e.printStackTrace才能(); ,} }利用弹簧怎么实现一个监听器功能