@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
@Component
public 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());
}
}