在监听器中使用@Autowried调用service层包null的解决方案

公司做热备份时,需要检测当前的硬件和卫星是否为告警状态,检测到后就新建一个标识(空文件)。

刚开始,我在监听器中调用server层后来获取需要的数据,发现始终是为空。于是参考了网站相关的资料发现是因为监听器是由servlet调用的,而@Autowried是由spring来进行管理的,结果当然为空咯。总结的以下几个解决方案:

【1】使用

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"/>


经过多次测试最终采用第三种方案,测试已通过。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值