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

本文介绍了一种在Spring MVC框架下,工具类如何正确调用由Spring管理的Service层的方法。通过将工具类声明为Spring组件,并利用@PostConstruct注解完成依赖注入,实现了工具类对Service层的有效调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文转载自: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);
			}	
		}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值