本文共 2152 字,大约阅读时间需要 7 分钟。
AspectJ使用org.aspectj.lang.JoinPoint接口表示目标类连接点对象,如果是环绕增强时,使用org.aspectj.lang.ProceedingJoinPoint表示连接点对象,该类是JoinPoint的子接口。任何一个增强方法都可以通过将第一个入参声明为JoinPoint访问到连接点上下文的信息。我们先来了解一下这两个接口的主要方法: 1)JoinPoint java.lang.Object[] getArgs():获取连接点方法运行时的入参列表; Signature getSignature() :获取连接点的方法签名对象; java.lang.Object getTarget() :获取连接点所在的目标对象; java.lang.Object getThis() :获取代理对象本身; /** * 声明一个注解 */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Action { String name();} @Servicepublic class DemoAnnotationService { @Action(name="注解式拦截的add操作") public void add(){ }} @Servicepublic class DemoMethodService { public void add(){}} @Aspect@Component //配置为beanpublic class LogAspect { @Pointcut("@annotation(com.wisely.aop.Action)")//申明一个切面,供重复使用 public void annotationPointCut(){} /** * joinPoint主要用于和被代理类交互,前面对该类有解释说明 * @param joinPoint */ @After("annotationPointCut()") public void after(JoinPoint joinPoint){ MethodSignature signature=(MethodSignature)joinPoint.getSignature(); Method method=signature.getMethod(); Action action=method.getAnnotation(Action.class); System.out.println("注解式拦截 "+action.name()); } @Before("execution(* com.wisely.aop.DemoMethodService.*(..))") public void before(JoinPoint joinPoint){ MethodSignature signature=(MethodSignature)joinPoint.getSignature(); Method method=signature.getMethod(); System.out.println("方法规则式拦截,"+method.getName()); }} @Configuration//该类为配置类@ComponentScan("com.wisely.aop")//扫描包下所有使用@Service,@Component,@Repository,@Controller的类并注册为bean@EnableAspectJAutoProxy //该注解用于开启Spring对AspectJ的支持public class AopConfig {} public class Main { public static void main(String[] args){ AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(AopConfig.class); DemoAnnotationService demoAnnotationService=context.getBean(DemoAnnotationService.class); DemoMethodService demoMethodService=context.getBean(DemoMethodService.class); demoAnnotationService.add(); demoMethodService.add(); context.close(); }}
转载地址:http://mojqi.baihongyu.com/