Aop之AspectJ

来源:互联网 发布:考公务员 知乎 编辑:程序博客网 时间:2024/06/05 18:26
  1. 编写拦截规则的注解
package com.example.aspectj;/* 忽略导包,方法都在同一个包下,后面省略 */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Action{    String name();}
  1. 编写使用注解被拦截的类
@Servicepublic class DemoAnnotationService {    @Action(name = "注解式拦截的add操作")    public void add(){        System.out.println("调用注解式拦截的add操作");    }}
  1. 编写使用方法规则拦截的类
@Servicepublic class DemoMethodService {    public void add(){        System.out.println("调用方法式拦截的add操作");    }}
  1. 编写切面
@Aspect //通过Aspect注解声明一个切面@Componentpublic class LogAspcet {    @Pointcut("@annotation(com.example.aspectj.Action)")  //通过Pointcut注解声明切点    public void annotationPointCut(){}    @After("annotationPointCut()") //通过After注解声明一个建言,并使用@Pointcut定义的切点    public void before(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.example.aspectj.DemoMethodService.*(..))") //通过@Before注解声明一个建言,直接使用拦截规则作为参数    public void after(JoinPoint joinPoint){        MethodSignature signature = (MethodSignature) joinPoint.getSignature();        Method method = signature.getMethod();        System.out.println("方法式拦截  " + method.getName());    }}
  1. 编写配置类
@Configuration@ComponentScan("com.example.aspectj")@EnableAspectJAutoProxy //开启spring对AspectJ的支持public class AopConfig {}
  1. 运行
@RunWith(SpringRunner.class)@SpringBootTestpublic class DemoApplicationTests {    @Test    public void contextLoads() {        AnnotationConfigApplicationContext context = new        AnnotationConfigApplicationContext(AopConfig.class);        DemoMethodService demoMethodService = context.getBean(DemoMethodService.class);        DemoAnnotationService demoAnnotationService = context.getBean(DemoAnnotationService.class);        demoAnnotationService.add();        demoMethodService.add();        context.close();    }}
  1. 控制台输出结果
    调用注解式拦截的add操作
    注解式拦截 注解式拦截的add操作
    方法式拦截 add
    调用方法式拦截的add操作
原创粉丝点击