在實際開發中,很多時刻我們會有記錄請求日志,定時任務日志等需求,在每個方法中都編寫相同的代碼去記錄日志顯然是不合理的。
Spring已經為我們提供了面向切面編程的思想,不妨簡單的使用下自定義注解。
簡單自定義注解分四步:
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:編寫自己的切面實現類,就是上文所說的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 { //標注該方法體為后置通知,當目標方法執行成功后執行該方法體 @AfterReturning("within(com.thc.tenantcenter..*) && @annotation(rl)") public void addLogSuccess(JoinPoint jp, LogAnnotation rl){ Object[] parames = jp.getArgs();//獲取目標方法體參數 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)
以上是簡單的自定義注解使用,希望能幫助初學者解決問題