201709
公司做热备份时,需要检测当前的硬件和卫星是否为告警状态,检测到后就新建一个标识(空文件)。
刚开始,我在监听器中调用server层后来获取需要的数据,发现始终是为空。于是参考了网站相关的资料发现是因为监听器是由servlet调用的,而@Autowried是由spring来进行管理的,结果当然为空咯。总结的以下几个解决方案:
【1】使用WebApplicationContextUtils
WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(HeartbeatDataService.class);
【2】使用@Postconstruct
【3】继承initializingBean接口:如下所示
public class CheckAlarm implements InitializingBean{ protected final Log logger = LogFactory.getLog(getClass()); @Resource private HeartbeatDataService heartbeatDataService; @Override public void afterPropertiesSet() throws Exception { new Thread(new Runnable() { @Override public void run() { //实时检测当前是否为告警状态 while(true){ String dirpath = "/home/run"; String downPath = dirpath+"/down"; File dir = new File(dirpath); File down = new File(downPath); //获取心跳包信息 HeartbeatData heartbeatData = heartbeatDataService.getHeartbeatData(); //检测是否为空 if(null == heartbeatData){ logger.error("heartbeat pack gets null,Can not create a 'down' file!"); break; } //若二者都不为空则删除down文件,反之则添加 if(heartbeatData.getSatellite() == 0 && heartbeatData.getDeviationValue() == 0){ if(!down.exists()) down.delete(); }else{ if(!dir.exists()) dir.mkdirs(); if(!down.exists()){ try { down.createNewFile(); } catch (IOException e) { logger.error("createNewFile error"); break; } } } } } }).start();; } }
最后在spring-web.xml添加相应配置
<bean id="checkAlarm" class="com.cdqihang.web.CheckAlarm"/>