1. 程式人生 > 其它 >springboot面向切面程式設計

springboot面向切面程式設計

 使用註解的方式可能要比使用配置檔案要慢,因為註解要呼叫反射,賊耗時,但是你不用再去在配置檔案上費心。實際上,在實際工作時,大部分都是使用註解的方式。

什麼是AOP
AOP就是通過動態為專案中某些類在執行過程中動態建立代理物件,在物件中完成附加功能,保證在處理業務時更加專注於自己的業務邏輯開發。
有以下幾個概念:
1.通知(Advice)——給目標方法新增額外操作稱之為通知,也可以稱為增強
2.連線點(Joinpoint)——就是可以增強的地方(方法的前後某個階段)
3.切入點(Pointcut)——實際增強的地方
4.切面(Aspect)——封裝了通知和切入點用來橫向插入的類
5.代理(Proxy)——將通知應用到目標類動態建立的物件
6.織入(Weaving)——將切面插入到目標從而生成代理物件的過程
————————————————
版權宣告:本文為CSDN博主「worilb」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/worilb/article/details/114156126

1、引入springboot-aop整合jar

          Spring-boot-start-aop

2、application.yml中啟用宣告

#spring配置
spring:
  #切面啟用
  aop:
    proxy-target-class: true
    auto: true
@Component
@Aspect //切面類註解
@Order(2)
public class AsceptTest {

    @Pointcut("execution(* com.study.service.UserService.eat(*))")
    private
void Myeat(){}; //前置通知。value匹配規則,也就是指定攔截的切入點(方法) // @Before(value = "execution(* com.study.service.UserService.eat(*))") // execution匹配某些方法效率,whithin匹配某些類(中的所有方法) @Before(value = "Myeat()") public void before(JoinPoint joinPoint){ System.out.println("當前方法名: "+joinPoint.getSignature().getName()); System.out.println(
"當前執行方法引數: "+joinPoint.getArgs()[0]); System.out.println("目標物件target: "+joinPoint.getTarget()); System.out.println("前置增強——保姆做飯"); } //後置通知 // @After(value = "execution(* com.study.service.UserService.eat(*))") @After("Myeat()") public void after(JoinPoint joinPoint){ System.out.println("當前方法名: "+joinPoint.getSignature().getName()); System.out.println("當前執行方法引數: "+joinPoint.getArgs()[0]); System.out.println("目標物件target: "+joinPoint.getTarget()); System.out.println("後置增強——保姆洗碗"); } //環繞通知 @Around(value = "execution(* com.study.service.UserService.out())" ) public Object round(ProceedingJoinPoint joinPoint) throws Throwable { //環繞增強必須要獲取ProceedingJoinPoint引數, System.out.println("當前方法名: "+joinPoint.getSignature().getName()); // System.out.println("當前執行方法引數: "+joinPoint.getArgs()[0]); 目標物件沒引數不可獲取 System.out.println("目標物件target: "+joinPoint.getTarget()); System.out.println("環繞增強——保安開門"); //目標方法執行前 Object proceed = joinPoint.proceed(); //執行目標方法 System.out.println("環繞增強——保安關門"); //目標方法執行後 return proceed; //返回目標方法執行結果 } //異常通知 @AfterThrowing(value = "within(com.study.service.UserService+)",throwing="e") public void ex(JoinPoint joinPoint,Exception e){ System.out.println("出錯了"+e.getMessage()); } //返回通知,方法正常返回則生效 @AfterReturning(value = "within(com.study.service.UserService+)",returning="result") public void ex(JoinPoint joinPoint,Object result){ System.out.println(joinPoint.getSignature().getName()+ ":返回通知生效"); System.out.println("返回了"+result); } }

也可以使用註解

package cn.annotation;
 
import java.lang.annotation.*;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description:  自定義註解,攔截service
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
    String description() default "";
}
package cn.annotation;
 
import cn.pojo.Action;
import cn.pojo.User;
import cn.service.ActionService;
import cn.utils.IpUtils;
import cn.utils.JsonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description: 切點類
 */
@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {
    //注入Service用於把日誌儲存資料庫,實際專案入庫採用佇列做非同步
    @Resource
    private ActionService actionService;
    //本地異常日誌記錄物件
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
    //Service層切點
    @Pointcut("@annotation(cn.annotation.SystemServiceLog)")
    public void serviceAspect(){
    }
 
    //Controller層切點
    @Pointcut("@annotation(cn.oa.annotation.SystemControllerLog)")
    public void controllerAspect(){
    }
 
    /**
     * @Description  前置通知  用於攔截Controller層記錄使用者的操作
     * @date 2018年9月3日 10:38
     */
 
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //讀取session中的使用者
        User user = (User) session.getAttribute("user");
 
        String ip = IpUtils.getIpAddr(request);
 
        try {
            //*========控制檯輸出=========*//
            System.out.println("==============前置通知開始==============");
            System.out.println("請求方法" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()));
            System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
            System.out.println("請求人:"+user.getUsername());
            System.out.println("請求ip:"+ip);
 
            //*========資料庫日誌=========*//
            Action action = new Action();
            action.setActionDes(getControllerMethodDescription(joinPoint));
            action.setActionType("0");
            action.setActionIp(ip);
            action.setUserId(user.getId());
            action.setActionTime(new Date());
            //儲存資料庫
            actionService.add(action);
 
        }catch (Exception e){
            //記錄本地異常日誌
            logger.error("==前置通知異常==");
            logger.error("異常資訊:{}",e.getMessage());
        }
    }
 
    /**
     * @Description  異常通知 用於攔截service層記錄異常日誌
     * @date 2018年9月3日 下午5:43
     */
    @AfterThrowing(pointcut = "serviceAspect()",throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint,Throwable e){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //讀取session中的使用者
        User user = (User) session.getAttribute("user");
        //獲取請求ip
        String ip = IpUtils.getIpAddr(request);
        //獲取使用者請求方法的引數並序列化為JSON格式字串
        String params = "";
        if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                params+= JsonUtils.objectToJson(joinPoint.getArgs()[i])+";";
            }
        }
        try{
            /*========控制檯輸出=========*/
            System.out.println("=====異常通知開始=====");
            System.out.println("異常程式碼:" + e.getClass().getName());
            System.out.println("異常資訊:" + e.getMessage());
            System.out.println("異常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
            System.out.println("方法描述:" + getServiceMethodDescription(joinPoint));
            System.out.println("請求人:" + user.getUsername());
            System.out.println("請求IP:" + ip);
            System.out.println("請求引數:" + params);
            /*==========資料庫日誌=========*/
            Action action = new Action();
            action.setActionDes(getServiceMethodDescription(joinPoint));
            action.setActionType("1");
            action.setUserId(user.getId());
            action.setActionIp(ip);
            action.setActionTime(new Date());
            //儲存到資料庫
            actionService.add(action);
        }catch (Exception ex){
            //記錄本地異常日誌
            logger.error("==異常通知異常==");
            logger.error("異常資訊:{}", ex.getMessage());
        }
    }
 
 
    /**
     * @Description  獲取註解中對方法的描述資訊 用於service層註解
     * @date 2018年9月3日 下午5:05
     */
    public static String getServiceMethodDescription(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;
    }
 
 
 
    /**
     * @Description  獲取註解中對方法的描述資訊 用於Controller層註解
     * @date 2018年9月3日 上午12:01
     */
    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;
    }
}

開始使用

    1)@SystemControllerLog(description = "")

          註解加在控制器中方法上面,括號裡寫上操作描述