效果java
xml開啓AOP配置apache
<aop:config proxy-target-class="false" /> <aop:aspectj-autoproxy /> <bean id="opLogAspectj" class="com.noob.aspectj.OpLogAspectj"></bean>
使用方式:ui
@OpLog(model = 99) public String test() {// do somethings } @RequiresPermissions("rule:delete") public Response<Integer> delete(String params, HttpServletRequest request) { // do somethings }
aspectj實現:spa
package com.noob.aspectj; import lombok.extern.slf4j.Slf4j; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface OpLog { int model() default 1; }
//表達式 @Pointcut(value = "@annotation(com.noob.annotation.OpLog)") //簽名 public void opLogPointcut(){} // 另外的寫法 @Around(value = "execution(@cn.utrust.trusts.config.OpLog * *.*(..)) && @annotation(opLog)" , argNames="opLog") @Around(value= "opLogPointcut() && @annotation(opLog)" ) public Object aroundLog(ProceedingJoinPoint point, OpLog opLog) throws Throwable{ Object obj = null; Object[] args = point.getArgs(); try { obj = point.proceed(args); } catch (Throwable e) { log.error("方法執行異常", e); } long endTime = System.currentTimeMillis(); MethodSignature signature = (MethodSignature) point.getSignature(); String methodName = signature.getDeclaringTypeName() + "." + signature.getName(); return obj; }
@Aspect @Slf4j public class OpLogAspectj { @Pointcut(value = "@annotation(org.apache.shiro.authz.annotation.RequiresPermissions)") public void permissionPointcut(){} @Around(value= "permissionPointcut() && (args(request, ..) || args(.., request))") public Object aroundPermission(ProceedingJoinPoint point, HttpServletRequest request) throws Throwable{ Object obj = null; Object[] args = point.getArgs(); try { SsoUser ssoUser = SsoSession.getCurrentUser(request); obj = point.proceed(args); } catch (Throwable e) { log.error("方法執行異常", e); } return obj; } }