基于spring@aspect注解的aop實現(xiàn)過程代碼實例
更新時間:2020年03月07日 10:53:33 作者:Mustr
這篇文章主要介紹了基于spring@aspect注解的aop實現(xiàn)過程代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
@AspectJ 作為通過 Java 5 注釋注釋的普通的 Java 類,它指的是聲明 aspects 的一種風格。通過在你的基于架構的 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 @Component public class AnnotationAspectJ { //定義切面("execution(* com.dascom.common.aop.*.*(..))) //當前配置的意思是所有添加了SuiteMessage的注解的方法作為切點 @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í)行時長(毫秒) 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"> <!-- 配置自動掃描的包 --> <context:component-scan base-package="com.dascom.hawk.app.web.tool"></context:component-scan> <!-- 自動為切面方法中匹配的方法所在的類生成代理對象。 proxy-target-class="true" 這個的作用是struts的控制類都基礎的actionSupport,必須添加這個,不然會報錯 --> <aop:aspectj-autoproxy proxy-target-class="true" /> </beans>
第三步:搞定。爽歪歪~~~
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java中notify和notifyAll的區(qū)別及何時使用
本文主要介紹了Java中notify和notifyAll的區(qū)別及何時使用,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09詳解在spring boot中消息推送系統(tǒng)設計與實現(xiàn)
這篇文章主要介紹了詳解在spring boot中消息推送系統(tǒng)設計與實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05Mybatis如何實現(xiàn)@Select等注解動態(tài)組合SQL語句
這篇文章主要介紹了Mybatis如何實現(xiàn)@Select等注解動態(tài)組合SQL語句,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07