静态工具类中使用注解注入service

一般需要在一个工具类中使用@Autowired 注解注入一个service。但是由于工具类方法一般都写成static,所以直接注入就存在问题。

使用如下方式可以解决:

/**
 * 
 */
package cn.ffcs.drive.common.util;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.ffcs.drive.domain.Admin;
import cn.ffcs.drive.domain.OpeLog;
import cn.ffcs.drive.service.IOpeLogService;
import cn.ffcs.zq.util.DateUtils;

/**
 * className:OpeLogUtils
 * 
 * 管理员操作日志
 * 
 * @author pengyh
 * @version 1.0.0
 * @date 2014-07-10 09:04:48
 * 
 */
@Component
public class OpeLogUtils {

	private static Logger logger = LoggerFactory.getLogger(OpeLogUtils.class);

	@Autowired
	private IOpeLogService opeLogService;
	private static OpeLogUtils opeLogUtils;

	public void setUserInfo(IOpeLogService opeLogService) {
		this.opeLogService = opeLogService;
	}
	
	@PostConstruct
    public void init() {
		opeLogUtils = this;
		opeLogUtils.opeLogService = this.opeLogService;

    }

	/**
	 * 执行操作日志入库操作
	 * @param adminId   管理员id
	 * @param opeDesc   操作日志信息
	 * @param cityCode  城市编码
	 */
	public static void insertOpeLog(HttpServletRequest req, String opeDesc) {
		try {
			/**
			 * 获取管理员信息
			 */
			Admin admin = DriveUtil.getSessionUser(req);
			
			if(admin != null && opeDesc != null && !opeDesc.trim().equals("")){
				
				//封装日志信息
				logger.info("开始封装日志信息。");
				OpeLog opeLog = new OpeLog();
				
				opeLog.setAdminId(admin.getId());
				opeLog.setCityCode(admin.getCityCode());
				opeLog.setOpeDesc("管理员id="+admin.getId()+"操作【"+opeDesc+"】");
				opeLog.setOpeTime(DateUtils.getNow());
				opeLog.setIsDelete("0");
				opeLogUtils.opeLogService.save(opeLog);
				
				logger.info("保存管理员操作日志成功,信息为【adminId:{},cityCode:{},opeDesc:{},opeTime:{}】",new Object[]{admin!=null?admin.getId():null,admin.getCityCode(),opeDesc,DateUtils.getNow()});
			}else{
				logger.info("保存操作日志失败,参数不足【adminId:{},cityCode:{},opeDesc:{},opeTime:{}】",new Object[]{admin!=null?admin.getId():null, admin!=null?admin.getCityCode():null, opeDesc, DateUtils.getNow()});
			}
		} catch (Exception e) {
			logger.error("保存操作日志异常,异常信息为:" + e.getMessage(), e);
		}
	}

}

  • 17
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 23
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有一只柴犬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值