靜態工具類中使用註解注入service
阿新 • • 發佈:2019-01-03
一般需要在一個工具類中使用@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); } } }