基于spring@aspect注解的aop實(shí)現(xiàn)過程代碼實(shí)例
@AspectJ 作為通過 Java 5 注釋注釋的普通的 Java 類,它指的是聲明 aspects 的一種風(fēng)格。通過在你的基于架構(gòu)的 XML 配置文件中包含以下元素,@AspectJ 支持是可用的。
第一步:編寫切面類
package com.dascom.hawk.app.web.tool;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;@Aspect@Componentpublic class AnnotationAspectJ { //定義切面('execution(* com.dascom.common.aop.*.*(..))) //當(dāng)前配置的意思是所有添加了SuiteMessage的注解的方法作為切點(diǎn) @Pointcut('@annotation(com.dascom.common.annotation.SuiteMessage)') public void logPointCut() { } //前置通知 @Before('logPointCut()') public void before(JoinPoint point) { String calssName = point.getTarget().getClass().getName(); String method = point.getSignature().getName(); System.out.println(calssName + ' : ' + method); } //后置通知 @After('logPointCut()') public void after(JoinPoint point) { String method = point.getSignature().getName(); System.out.println(method + ': end----'); } //環(huán)繞通知 @Around('logPointCut()') public Object around(ProceedingJoinPoint point) throws Throwable { long beginTime = System.currentTimeMillis(); // 執(zhí)行方法 Object result = point.proceed(); // 執(zhí)行時(shí)長(毫秒) long time = System.currentTimeMillis() - beginTime; //異步保存日志 System.out.println(time); return result; }}
第二步:在spring的配置文件中添加注解掃描
<?xml version='1.0' encoding='UTF-8'?><beans xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:aop='http://www.springframework.org/schema/aop' xmlns:context='http://www.springframework.org/schema/context' xsi:schemaLocation='http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd'> <!-- 配置自動(dòng)掃描的包 --> <context:component-scan base-package='com.dascom.hawk.app.web.tool'></context:component-scan> <!-- 自動(dòng)為切面方法中匹配的方法所在的類生成代理對象。 proxy-target- 這個(gè)的作用是struts的控制類都基礎(chǔ)的actionSupport,必須添加這個(gè),不然會(huì)報(bào)錯(cuò) --> <aop:aspectj-autoproxy proxy-target- /> </beans>
第三步:搞定。爽歪歪~~~
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析2. 一個(gè) 2 年 Android 開發(fā)者的 18 條忠告3. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程6. Android studio 解決logcat無過濾工具欄的操作7. 什么是Python變量作用域8. vue-drag-chart 拖動(dòng)/縮放圖表組件的實(shí)例代碼9. Spring的異常重試框架Spring Retry簡單配置操作10. Vue實(shí)現(xiàn)仿iPhone懸浮球的示例代碼
