Spring注入service为null另类解决办法 工具类 一般类 静态 非controller

2023-11-15

本文转载自:http://www.cnblogs.com/allforone/p/4108862.html

 系统为SpringMVC框架,在开发的过程中有一些工具类需要调用下由spring管理的service层。但是一进注入不进来,报null异常;

      在尝试了网上的一系列方法后,还是没有解决。网上的解决方法主要有以下几种:

        1、将工具类申明为spring组件,如@controller @compent 等,在spring自动扫描包设置中将工具类所在的包加进来;  无效  

        2、new一个service;  无效 而且不符合spring管理;

      山穷水尽后,找到了一个另类的解决办法,代码原理还不太清楚,只是大概猜测下,有错误的地方,大家留言指正:

  1. @Component     //申明为spring组件
  2. public class TestUtils {  
  3.     @Autowired    
  4.     private TestService testService;  //添加所需service的私有成员
  5.     private static TestUtils  testUtils ;  //  关键点1   静态初使化 一个工具类  这样是为了在spring初使化之前
  6.   
  7.     public void setTestService(TestService  testService) {  
  8.         this.testService = testService;  
  9.     }  
  10.       
  11.     @PostConstruct     //关键二   通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
  12.     public void init() {  
  13.         testUtils = this;  
  14.         testUtils.testService = this.testService;   // 初使化时将已静态化的testService实例化
  15.     }  

                这样下面的代码中就可以通过 testUtils.testService 来调用service处理


实例代码

package com.common.common.util.model;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.common.common.util.BaseGateWay;
import com.common.common.util.SpringContextUtil;
import com.smart.entity.HomeDevice;
import com.smart.entity.HomeDeviceAttrStatu;
import com.smart.entity.HomeDeviceCommand;
import com.smart.entity.HomeDeviceLog;
import com.smart.entity.HomeGateway;
import com.smart.service.IHomeDeviceAttrStatuService;
import com.smart.service.IHomeDeviceLogService;
import com.smart.service.IHomeDeviceService;
import com.smart.service.IHomeGatewayService;
//网格报警器
@Component
public class GridAlarm implements BaseGateWay {
	@Autowired
	private IHomeDeviceService homeDeviceService ;	
	@Autowired
	private IHomeDeviceLogService deviceLogService;
	@Autowired
	private IHomeDeviceAttrStatuService deviceAttrStatuService;
	@Autowired
	private IHomeGatewayService gatewayService; 
	
	private static GridAlarm  util;

	public void setHomeDeviceService(IHomeDeviceService homeDeviceService) {
		this.homeDeviceService = homeDeviceService;
	}
	public void setDeviceLogService(IHomeDeviceLogService deviceLogService) {
		this.deviceLogService = deviceLogService;
	}
	public void setDeviceAttrStatuService(
			IHomeDeviceAttrStatuService deviceAttrStatuService) {
		this.deviceAttrStatuService = deviceAttrStatuService;
	}
	public void setGatewayService(IHomeGatewayService gatewayService) {
		this.gatewayService = gatewayService;
	}
	
	@PostConstruct
	public void init(){
		util =this;
		util.deviceAttrStatuService = this.deviceAttrStatuService;
		util.deviceLogService = this.deviceLogService;
		util.gatewayService = this.gatewayService;
		util.homeDeviceService = this.homeDeviceService;
	}



	@Override
	public HomeDeviceCommand getHomeDeviceCommand(Map<String, Object> services) {
		// TODO Auto-generated method stub
		HomeDeviceCommand devCommandObj = new HomeDeviceCommand();
		String command_type =" ";
		String command_code =" ";
		String comand =" ";
		if(services.get("infrared_alarm")!=null){
			//能力代码
			command_type = "infrared_alarm";
			//特征值代码
			command_code = "alarm";
			//更新网关布防状态
			Map map = (Map)services.get(command_type);
			comand = map.get(command_code).toString();
			//不发短信
			//issms = 0;
		}
		if(services.get("smoke_alarm")!=null){
			//能力代码
			command_type = "smoke_alarm";
			//特征值代码
			command_code = "alarm";
			//更新网关布防状态
			Map map = (Map)services.get(command_type);
			comand = map.get(command_code).toString();
			//不发短信
			//issms = 0;
		}
		if(services.get("alarm_switch")!=null){
			//能力代码
			command_type = "alarm_switch";
			//特征值代码
			command_code = "on_off";
			//更新网关布防状态
			Map map = (Map)services.get(command_type);
			comand = map.get(command_code).toString();
		}		
		devCommandObj.setCommand(comand);
		devCommandObj.setCommandType(command_type);
		devCommandObj.setCommandCode(command_code);
		return devCommandObj;
	}

	

	@Override
	public void proceNotice(Map<String, Object> services,
			List<HomeGateway> gatewayList, int gateway_id, String device_id_,
			Integer device_code_, String gateway_uid, HomeDevice device_,
			Integer device_type) {
		// TODO Auto-generated method stub
		if(services.get("operation_status")!=null){
			Map map = (Map)services.get("operation_status");
			if(gatewayList != null && gatewayList.size()>0){
				if((int)map.get("status")==1){
					this.UpdateRestOnLineDevice(gateway_id, device_id_, 1);
				}else if((int)map.get("status")==-1){
					//删除该子设备
					Map<String, Object> maps = new HashMap<String, Object>();
					maps.put("device_uid", device_id_);
					maps.put("gateway_uid", gateway_uid);
					maps.put("gateway_id", gateway_id);

					util.homeDeviceService.deleteDeviceByUId(maps);
				}else{
					System.out.println("1234");
					this.UpdateOffLineDevice(gateway_id, device_id_, 1);
				}
			}
		}
		if(services.get("alarm_switch")!=null){
			//能力代码
			String command_type = "alarm_switch";
			//特征值代码
			String command_code = "on_off";
			//更新网关布防状态
			Map map = (Map)services.get(command_type);
			String comand = map.get(command_code).toString();

			String desc = "布防";
			if(comand.equals("0")){
				desc = "撤防";
			}
			//保存日志
			this.SaveDeviceLog(gateway_id, device_.getId(), comand, desc,gateway_uid,device_.getDeviceUid(),device_.getDeviceName());

			this.SaveAlarmAttrStatus(device_.getId(), device_code_,command_type, command_code, comand, desc);

			if(device_id_.equals(gateway_uid)&&device_code_ == device_type){
				//网关修改布防撤防状态
				Map<String,Object> maps = new HashMap<String,Object>();
				int stat = 1;
				if(Integer.parseInt(comand) == 0){
					stat = 0;
				}
				maps.put("status", stat);
				maps.put("gateway_uid", gateway_uid);
				util.gatewayService.updateGatewayStatus(maps);
			}
		}
		
		if(services.get("auto_alarm_time")!=null){	//定时警戒
			//能力代码
			String command_type = "auto_alarm_time";
			//特征值代码
			String command_code = "";

			//更新网关布防状态
			Map map = (Map)services.get(command_type);

			String comand = JSONObject.toJSONString(map);
			//保存日志
			this.SaveDeviceLog(gateway_id, device_.getId(), command_type, comand,gateway_uid,device_.getDeviceUid(),device_.getDeviceName());

			this.SaveAlarmAttrStatus(device_.getId(), device_code_,command_type, command_code, comand, "警戒时间");
		}
		
		
		
		
		
	}
	
		//更新重新上线设备状态
		private void UpdateRestOnLineDevice(int gatewayId,String deviceId,Integer typeCode) {
			HomeDevice restOnLineDevObj = new HomeDevice();
			restOnLineDevObj.setGatewayId(gatewayId);
			restOnLineDevObj.setTypeCode(typeCode);
			restOnLineDevObj.setDeviceUid(deviceId);
			restOnLineDevObj.setStatus("1");
			restOnLineDevObj.setUpTime(new Date());
			util.homeDeviceService.updateDeviceOffLine(restOnLineDevObj);//更新重新上线设备状态
		}
		//更新掉线设备状态
		private void UpdateOffLineDevice(int gatewayId,String deviceId,Integer typeCode) {
			HomeDevice offLineDevObj = new HomeDevice();
			offLineDevObj.setGatewayId(gatewayId);
			offLineDevObj.setTypeCode(typeCode);
			offLineDevObj.setDeviceUid(deviceId);
			offLineDevObj.setStatus("0");
			offLineDevObj.setUpTime(new Date());
			util.homeDeviceService.updateDeviceOffLine(offLineDevObj);//更新掉线设备状态
		}
		
		//保存设备日志
		private void SaveDeviceLog(int gatewayId,int deviceId,String command,String commandDesc,String gatewayUid,String deviceUid,String deviceName) {
			//日志
			//"type_code":"0103","device_uid":"3"
			HomeDeviceLog devLogObj = new HomeDeviceLog();
			devLogObj.setGatewayUid(gatewayUid);
			devLogObj.setDeviceUid(deviceUid);
			devLogObj.setDeviceName(deviceName);
			devLogObj.setGatewayId(gatewayId);
			devLogObj.setDeviceId(deviceId);
			devLogObj.setMsgType("log");
			devLogObj.setMsgCommand(command);
			devLogObj.setMsgContent(commandDesc);
			devLogObj.setCreatedTime(new Date());
			devLogObj.setUpTime(new Date());
			devLogObj.setDelFlag(0);
			util.deviceLogService.insertDeviceLog(devLogObj);
		}
		
		//保存设备上报上来属性
		public void SaveAlarmAttrStatus(int device_id,Integer type_code,String command_type,String command_code,String comand,String command_desc){

			//保存到设备属性表中
			HomeDeviceAttrStatu record = new HomeDeviceAttrStatu();
			record.setDeviceId(device_id);
			record.setTypeCode(type_code);
			record.setCommandType(command_type);
			record.setCommandCode(command_code);
			record.setComand(comand);
			record.setComandDesc(command_desc);
			record.setCreatedTime(new Date());
			record.setUpTime(new Date());
			record.setDelFlag(0);

			if(util.deviceAttrStatuService.selectExistsDeviceAttr(record)>0){
				util.deviceAttrStatuService.updateDeviceAttr(record);
			}else{
				util.deviceAttrStatuService.insertDeviceAttr(record);
			}	
		}

}


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring注入service为null另类解决办法 工具类 一般类 静态 非controller 的相关文章

  • 超级详细的 Maven 教程(基础+高级)

    1 Maven 是什么 Maven 是 Apache 软件基金会组织维护的一款专门为 Java 项目提供构建和依赖管理支持的工具 一个 Maven 工程有约定的目录结构 约定的目录结构对于 Maven 实现自动化构建而言是必不可少的一环 就
  • PROFIBUS DP从站开发 VPC3源程序分析---user_chk_new_cfg_data(void)

    以下程序注释由成都地质学院霸王猫添加 引用时请尊重作者劳动成果 标明引用者来自成都地质学院霸王猫 UBYTE user chk new cfg data void 入口参数 无 出口参数 无 返回值 VPC3 CFG OK VPC3 CFG
  • SLAM-hector_slam 简介与使用

    hector slam功能包使用高斯牛顿方法 不需要里程计数据 只根据激光信息便可构建地图 所以他的总体框架如下 hector slam功能包 hector slam的核心节点是hector mapping 它订阅 scan 话题以获取SL
  • git-linux-xll?x11-unix 挖矿病毒问题定位与处理

    1 dev服务器出现git用户启动的进程cpu200 的情况 网络传输在高速流量流出 2 首先关停gitlab服务 3 杀死进程后 会马上再出现 无定时任务 4 使用lsof p PID 查看 其中一个名字为 xll unix的文件 该文件
  • put_user

    Linux设备驱动开发笔记 1 复制链接 0 0 skyily 白手起家 帖子 108 主题 105
  • 分组对列扁平化(列转换行 关系型转换NoSQL)

    前言 关系型数据库要符合第一范式即原子性 因此字段多值情况只能分行处理 如下表 假设keys是terms appl dt 则no predict pay dt actual pay dt 是多值 如果要转换成NoSQL或collection
  • 连续七天登录-在线人数最多

    连续七天登录 select id count from select date add dated rown as startdate from select row number over PARTITION by id order by
  • 随笔篇-多线程世界的来龙去脉

    文章目录 线程 多线程带来的问题 线程的挂起与唤醒 线程的管理 如果看官觉得有点用 点赞一下 鼓励一下我吧 感谢原创的整理 以下是原文作者连接 原文 https zhuanlan zhihu com p 122010626 以下为摘抄概要整
  • JSP数据交互(二)----》浏览器缓存cookie

    学会使用浏览器缓存cookie 生活中的cookie 系统会记录已经浏览过的搜索记录 cookie是Web服务器保存在客户端的一系列文本信息 cook的作用 对特定的对象追踪 实现各种个性化功能 简化登录 安全性能 容易泄露信息 在JSP中
  • Latex 操作(3) beamer(PPT)

    1 新建文件 documentclass 11pt beamer 11pt 是设置的字号大小 usetheme CambridgeUS 排版主题Madrid 在每个section前有一个current显示 放到引言区 在每个section前

随机推荐