天天看點

spring aop的案例(一)日志攔截

日志攔截,一般主要在service和action進行日志攔截。這裡我們直接講用法,至于原理就不做具體講解。

我們使用spring+spring mvc架構項目

aplicationContext-common.xml:

<context:component-scan base-package="com.tonghui.thcws">
        <!--删除controller注解掃描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>   

<!-- 啟動對@AspectJ注解的支援 -->  
<aop:aspectj-autoproxy/> 
<!--事務注解-->
<tx:annotation-driven  transaction-manager="transactionManager" proxy-target-class="true" />
           

applicationContext-mvc.xml:

<context:component-scan base-package="com.tonghui.thcws.web.controller">
    <!--隻掃描controller注解-->    
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
</context:component-scan>
           
Log注解聲明:SystemLogAspect.java
import java.lang.reflect.Method;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.tonghui.cws.vo.Principal;
import com.tonghui.thcws.model.SysLog;
import com.tonghui.thcws.service.SysLogService;

/**
 * 切點類
 * 
 * @author 崔金睿
 * @since 2015年6月24日 10:17:51
 * @version 1.0
 */
@Aspect
@Component
public class SystemLogAspect {
    // 注入Service用于把日志儲存資料庫
    @Autowired
    private SysLogService logService;
    // 本地異常日志記錄對象
    private static final Logger logger = LoggerFactory
            .getLogger(SystemLogAspect.class);

    // Service層切點
    @Pointcut("@annotation(SystemServiceLog)")
    public void serviceAspect() {
    }

    // Controller層切點
    @Pointcut("@annotation(SystemControllerLog)")
    public void controllerAspect() {
    }

    private String getUser() {
        Subject subject = SecurityUtils.getSubject();
        Principal principal=    (Principal) subject.getPrincipal();
        return principal==null?"未登入使用者":principal.getUsername();
    }

    /**
     * 前置通知 用于攔截Controller層記錄使用者的操作
     * 
     * @param joinPoint
     *            切點
     */
    @After("controllerAspect()")
    public void doAfter(JoinPoint joinPoint) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        // 請求的IP
        String ip = request.getRemoteAddr();
        // 擷取使用者請求方法的參數并序列化為JSON格式字元串
                StringBuffer params = new StringBuffer();
                if (joinPoint.getArgs() != null && joinPoint.getArgs().length > ) {
                    params.append("[");
                    for (int i = ; i < joinPoint.getArgs().length; i++) {
                        params.append(joinPoint.getArgs()[i]);
                        params.append(",");
                    }
                    params.deleteCharAt(params.length()-);
                    params.append("]");
                }
        try {
            // *========資料庫日志=========*//
            SysLog log = new SysLog();
            log.setType("0");// 0錄使用者的記錄檔 1為異常日志
            log.setCreateBy(getUser());
            log.setCreateDate(new Date());

            log.setRemoteAddr(ip);
            log.setUserAgent(request.getHeader("User-Agent"));
            log.setRequestUri(request.getRequestURI());
            log.setMethod((joinPoint.getTarget().getClass().getName() + "."
                    + joinPoint.getSignature().getName() + "()"));
            log.setDescription(getControllerMethodDescription(joinPoint));

            // 參數
            log.setParams(params.toString());
            log.setExceptionCode(null);
            log.setExceptionDetail(null);
            // 儲存資料庫
            logService.addLog(log);
        } catch (Exception e) {
            // 記錄本地異常日志
            logger.error("==前置通知異常==");
            logger.error("異常資訊:{}", e.getMessage());
        }
    }
    /**
     * 異常通知 用于攔截serviceAspect層記錄異常日志
     * 
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        // 擷取請求ip
        String ip = request.getRemoteAddr();
        // 擷取使用者請求方法的參數并序列化為JSON格式字元串
        StringBuffer params = new StringBuffer();
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > ) {
            params.append("[");
            for (int i = ; i < joinPoint.getArgs().length; i++) {
                params.append(joinPoint.getArgs()[i]);
                params.append(",");
            }
            params.deleteCharAt(params.length()-);
            params.append("]");
        }
        try {
            // *========資料庫日志=========*//
            SysLog log = new SysLog();

            log.setType("1");// 0錄使用者的記錄檔 1為異常日志
            log.setCreateBy(getUser());
            log.setCreateDate(new Date());

            log.setRemoteAddr(ip);
            log.setUserAgent(request.getHeader("User-Agent"));
            log.setRequestUri(request.getRequestURI());
            log.setMethod((joinPoint.getTarget().getClass().getName() + "."
                    + joinPoint.getSignature().getName() + "()"));
            log.setDescription(getControllerMethodDescription(joinPoint));

            // 參數
            log.setParams(params.toString());
            log.setExceptionCode(e.getClass().getName());
            log.setExceptionDetail(e.getMessage());
            // 儲存資料庫
            logService.addLog(log);
        } catch (Exception ex) {
            // 記錄本地異常日志
            logger.error("==異常通知異常==");
            logger.error("異常資訊:{}", ex.getMessage());
        }
        /* ==========記錄本地異常日志========== */
        logger.error("異常方法:{}異常代碼:{}異常資訊:{}參數:{}", joinPoint.getTarget()
                .getClass().getName()
                + joinPoint.getSignature().getName(), e.getClass().getName(),
                e.getMessage(), params);

    }

    /**
     * 擷取注解中對方法的描述資訊 用于service層注解
     * 
     * @param joinPoint
     *            切點
     * @return 方法描述
     * @throws Exception
     */
    @Deprecated
    public static String getServiceMthodDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SystemServiceLog.class)
                            .description();
                    break;
                }
            }
        }
        return description;
    }

    /**
     * 擷取注解中對方法的描述資訊 用于Controller層注解
     * 
     * @param joinPoint
     *            切點
     * @return 方法描述
     * @throws Exception
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(
                            SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}
           
Controller日志攔截注解類:SystemControllerLog.java
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** 
 *自定義注解 攔截Controller 
 */ 
@Target({ElementType.PARAMETER, ElementType.METHOD})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented
public @interface SystemControllerLog {
    String description()  default "";
}
           
Service異常日志攔截注解類:SystemServiceLog.java
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** 
 *自定義注解 攔截Service
 */ 
@Target({ElementType.PARAMETER, ElementType.METHOD})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented
public @interface SystemServiceLog {
    String description()  default "";
}
           
如何使用?

Controller:

@SystemControllerLog(description ="賬戶啟用賬戶")
@RequestMapping(value ="/accountStart",method=RequestMethod.POST)
@ResponseBody
public JsonVO accountStart(Long id){
    JsonVO j = new JsonVO();
    try {
        accountService.accountEnable(id);
        j.setStatus(CwsConstants.STATUS_SUCCESS);
        j.setMessage("啟停成功!");
    } catch (Exception e) {
        j.setMessage("賬戶啟用失敗!");
        j.setStatus(CwsConstants.STATUS_ERROR);
        logger.error("賬戶啟用失敗",e.getMessage());
    }
    return j;
}
           

Service:

@SystemServiceLog(description="儲存賬戶發生異常")
@Transactional
public void save(CwsAccount entity) throws Exception{
    try {
        sqlSession.insert(DOMAIN_NAME+".insertSelective",entity);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}
           

使用的過程中會發現,service捕捉異常的時候會出現事務復原的現象,為什麼?如何解決?

原因是因為aop的先後順序導緻,剛剛寫入資料庫就被事務攔截後并發生異常則復原操作了。

<!--事務注解-->
<tx:annotation-driven  transaction-manager="transactionManager" proxy-target-class="true" order="2" />
           
這樣就實作了我們自己寫的aop在事務介入之前就執行了!