【資料圖】
專題使用匯總:
8. Java-AOP
1.AOP:面向切面編程,就是面向特定方法編程。在不改變?cè)蟹椒ǖ幕A(chǔ)上新增功能(功能增強(qiáng),功能改變)2.SpringAOP3.SpringAOP 開發(fā)步驟;
一.使用場(chǎng)景:1.記錄操作日志2.權(quán)限控制3.事務(wù)管理4.記錄方法執(zhí)行時(shí)間
二.優(yōu)勢(shì)1.代碼無(wú)浸入2.減少重復(fù)代碼3.提高開發(fā)效率4.維護(hù)方便
三.操作:執(zhí)行流程,動(dòng)態(tài)代理技術(shù),生成動(dòng)態(tài)代理對(duì)象(實(shí)現(xiàn)功能增強(qiáng))3.1 添加依賴在pom.xml
org.springframework.boot spring-boot-starter-aop
3.2 編寫AOP程序:針對(duì)特定方法業(yè)務(wù)需要進(jìn)行編程
@Slf4j@Component//@Aspect //AOP類public class TimeAspect { //@Around("execution(* com.itheima.service.impl.DeptServiceImpl.*(..))") //切入點(diǎn)表達(dá)式,對(duì)所有類,接口記錄執(zhí)行時(shí)間 @Around("com.itheima.aop.MyAspect1.pt()") public Object recordTime(ProceedingJoinPoint joinPoint) throws Throwable { //1. 記錄開始時(shí)間 long begin = System.currentTimeMillis(); //2. 調(diào)用原始方法運(yùn)行 Object result = joinPoint.proceed(); //3. 記錄結(jié)束時(shí)間, 計(jì)算方法執(zhí)行耗時(shí) long end = System.currentTimeMillis(); log.info(joinPoint.getSignature()+"方法執(zhí)行耗時(shí): {}ms", end-begin); return result; }}
四.核心概念1.連接點(diǎn): JoinPoint 可以被AOP控制的方法2.通知:Advice 指那些重復(fù)的邏輯,即共性的功能3.切入點(diǎn):PointCut 匹配連接點(diǎn)的條件
@Pointcut("execution(* com.itheima.service.impl.DeptServiceImpl.*(..))") public void pt(){} @Pointcut("execution(* com.itheima.service.DeptService.list()) || " + "execution(* com.itheima.service.DeptService.delete(java.lang.Integer))") private void pt(){}
[責(zé)任編輯:linlin]
標(biāo)簽: