Spring boot 中切面的實現

2021-10-05 19:21:02 字數 2184 閱讀 1060

這篇寫的不錯 spring aop

org.springframework.boot

spring-boot-starter-aop

/**

*操作日誌,切面處理類

* @author dxayga

* @aspect 作用是把當前類標識為乙個切面供容器讀取

* @component 交給 spring 管理

*/@aspect

@component

public class logaspect

對於註解的用法可以看看這篇 @pointcut 詳解

最常用的兩個表示式execution@annotation

execution(modifier-pattern?ret-type-patterndeclaring-type-pattern?name-pattern(param-pattern))

modifier-pattern? :訪問修飾符匹配,如public 表示匹配公有方法

ret-type-pattern:返回值型別匹配,* 表示任何返回值,全路徑的類名等

declaring-type-pattern? :類路徑匹配

name-pattern:方法名匹配,* 代表所有,set*,代表以set開頭的所有方法

param-pattern:引數匹配

如 @pointcut("execution(public * com.cork.service.sysroleservice.list(..))")

@pointcut("execution(public * com.cork.service.sysroleservice.list(..))")

public void logpointcut()

首先寫乙個註解 自定義註解

@pointcut("@annotation(com.cork.annotation.log)")

public void logpointcut()

@before在切點方法之前執行

@after在切點方法之後執行

@afterreturning切點方法返回後執行

@afterthrowing切點方法拋異常執行

@around屬於環繞增強,能控制切點執行前,執行後,,用這個註解後,程式拋異常,會影響@afterthrowing這個註解

@pointcut("@annotation(com.cork.annotation.log)")

public void logpointcut()

@before("logpointcut()")

public void before(joinpoint point) throws throwable

@after("logpointcut()")

public void after(joinpoint point) throws throwable

@around("logpointcut()")

public object around(proceedingjoinpoint point) throws throwable

@afterreturning("logpointcut()")

public void afterreturning(joinpoint point)

@afterthrowing("logpointcut()")

public void afterthrowing(joinpoint point)

要注意的是環繞通知的proceedingjoinpoint.proceed()方法,代表呼叫目標方法和返回值

AOP切面的實現

aop的全稱是aspect orient programming,即面向切面程式設計。是對oop object orient programming 的一種補充,戰門用於處理一些具有橫切性質的服務。常常用於日誌輸出 安全控制等。最近遇到增加操作日誌記錄功能問題,網上推薦使用切面技術實現,可以在不修改...

SpringBoot系列 aop 面向切面

org.springframework.boot spring boot starter aop aspect 切面 日誌切面 aspect component public class logaspect 環繞通知 around value weblog public object arround...

Spring Aop 切面的應用 註解

本次記錄的是使用spring註解的方式來實現切面程式設計.實現環境 設定乙個分布式鎖,在修改資料的時候,判斷鎖,加鎖,完成資料修改後,釋放鎖.自定義乙個鎖註解,新增到方法上,在執行方法前根據引數設定鎖key,target retention retentionpolicy.runtime publi...