日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring自定义注解简单使用四步走

發(fā)布時間:2024/4/14 javascript 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring自定义注解简单使用四步走 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在實際開發(fā)中,很多時刻我們會有記錄請求日志,定時任務日志等需求,在每個方法中都編寫相同的代碼去記錄日志顯然是不合理的。

Spring已經(jīng)為我們提供了面向切面編程的思想,不妨簡單的使用下自定義注解。

簡單自定義注解分四步:

1:在配置中打開aop編程

<!-- 自定義AOP --><aop:aspectj-autoproxy proxy-target-class="true"><aop:include name="serviceAspect" /></aop:aspectj-autoproxy><bean id = "serviceAspect" class="com.thc.tenantcenter.aspect.LogAspect"></bean>

 class指向的是切面解析類下文會有提到

2:編寫自己自定義的注解

package com.thc.tenantcenter.aspect;import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface LogAnnotation {String desc() default "打印日志"; }

3:編寫自己的切面實現(xiàn)類,就是上文所說的bean指向的路徑

package com.thc.tenantcenter.aspect;import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component;@Aspect //該注解標示該類為切面類 @Component //注入依賴 public class LogAspect { //標注該方法體為后置通知,當目標方法執(zhí)行成功后執(zhí)行該方法體 @AfterReturning("within(com.thc.tenantcenter..*) && @annotation(rl)") public void addLogSuccess(JoinPoint jp, LogAnnotation rl){ Object[] parames = jp.getArgs();//獲取目標方法體參數(shù) for (int i = 0; i < parames.length; i++) { System.out.println(parames[i]); } System.out.println(jp.getSignature().getName()); String className = jp.getTarget().getClass().toString();//獲取目標類名 System.out.println("className:" + className);className = className.substring(className.indexOf("com")); String signature = jp.getSignature().toString();//獲取目標方法簽名 System.out.println("signature:" + signature);} }

?4:在com.thc.tenantcenter包下及子包下方法上添加自己定義的注解

?

@LogAnnotation(desc = "通過ID獲取實體信息")@Override public AdminLog getAdminLogById(Integer id) { return adminLogMapper.getAdminLogById(id); }

?

?

?

? 運行結果為:

1
getAdminLogById
className:class com.thc.tenantcenter.biz.adminlog.service.impl.AdminLogServiceImpl
signature:AdminLog com.thc.tenantcenter.biz.adminlog.service.impl.AdminLogServiceImpl.getAdminLogById(Integer)

以上是簡單的自定義注解使用,希望能幫助初學者解決問題

?

轉載于:https://www.cnblogs.com/zhuxiansheng/p/7805552.html

總結

以上是生活随笔為你收集整理的Spring自定义注解简单使用四步走的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。