@within(com.cxh.study.aop.controller.UserAccessAnnotation)
表示攔截含有com.cxh.study.aop.controller.UserAccessAnnotation這個註解的類中所有方法
@annotation(com.cxh.study.aop.controller.UserAccessAnnotation)
表示攔截含有這個註解的方法
注意:如果在方法參數上需要該註解,則在運算式中不寫類名,而是寫參數名; 如果攔截的方法上有註解,則可以直接在方法上加入參數就可以取得,如果註解在Class上則需要使用ProceedingJoinPoint通過反射取得註解
樣本
package com.cxh.study.aop.controller;import org.apache.commons.logging.LogFactory;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;/** * Created by Jackie on 2015/4/20. * Email : cxh5060@163.com */@Aspect@Componentpublic class LoginInterceptor { /** * A Join Point is defined in the action layer where the method needs * a permission check. */ @Autowired private HttpServletRequest httpServletRequest; @Pointcut("@annotation(com.cxh.study.aop.controller.UserAccessAnnotation)") public void userAccess() {} /** * 這裡需要取得userAccessAnnotation, * 如果註解是在方法上,可以得到,如果註解在類上則為null * @param proceedingJoinPoint * @param userAccessAnnotation * @throws Throwable */ @Around(value = "@within(userAccessAnnotation) || " + "@annotation(userAccessAnnotation)") public void beforeMethod(ProceedingJoinPoint proceedingJoinPoint, UserAccessAnnotation userAccessAnnotation) throws Throwable{ System.out.println("method starts"); proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs()); proceedingJoinPoint.getTarget().getClass(); } /** * 這裡不需要取得userAccessAnnotation * @param proceedingJoinPoint * @throws Throwable */ @Around(value = "@within(com.cxh.study.aop.controller.UserAccessAnnotation) || " + "@annotation(com.cxh.study.aop.controller.UserAccessAnnotation)") public void beforeMethod1(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{ System.out.println("method starts"); proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs()); proceedingJoinPoint.getTarget().getClass(); } @AfterReturning("userAccess()") public void afterMethod(){ System.out.println("method ends"); } @Before(value = "@within(com.cxh.study.aop.controller.UserAccessAnnotation) || @annotation(com.cxh.study.aop.controller.UserAccessAnnotation)") public void before(JoinPoint joinPoint) throws Throwable { LogFactory.getLog(this.getClass()).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName()); } @After(value = "@within(com.cxh.study.aop.controller.UserAccessAnnotation) || @annotation(com.cxh.study.aop.controller.UserAccessAnnotation)") public void after(JoinPoint joinPoint) throws Throwable { LogFactory.getLog(this.getClass()).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName()); }}