Aop之AspectJ
来源:互联网 发布:考公务员 知乎 编辑:程序博客网 时间:2024/06/05 18:26
- 编写拦截规则的注解
package com.example.aspectj;/* 忽略导包,方法都在同一个包下,后面省略 */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Action{ String name();}
- 编写使用注解被拦截的类
@Servicepublic class DemoAnnotationService { @Action(name = "注解式拦截的add操作") public void add(){ System.out.println("调用注解式拦截的add操作"); }}
- 编写使用方法规则拦截的类
@Servicepublic class DemoMethodService { public void add(){ System.out.println("调用方法式拦截的add操作"); }}
- 编写切面
@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()); }}
- 编写配置类
@Configuration@ComponentScan("com.example.aspectj")@EnableAspectJAutoProxy //开启spring对AspectJ的支持public class AopConfig {}
- 运行
@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(); }}
- 控制台输出结果
调用注解式拦截的add操作
注解式拦截 注解式拦截的add操作
方法式拦截 add
调用方法式拦截的add操作
阅读全文
1 0
- Java AOP 之 AspectJ
- Java AOP 之 AspectJ
- Spring AOP之AspectJ
- AOP之Aspectj案例
- Spring AOP之AspectJ
- AOP之AspectJ
- Aop之AspectJ
- AOP笔记之AspectJ
- Spring Aop入门之Aspectj
- AOP技术学习之AspectJ
- AOP之AspectJ技术总汇
- AOP架构之路-AspectJ
- Spring aop之使用AspectJ
- AOP之使用AspectJ案例
- Spring AOP之增强(aspectj)
- AOP框架之:Spring AOP和AspectJ
- AOP框架之:Spring AOP和AspectJ
- AOP框架之:Spring AOP和AspectJ
- JSON 必知必会
- FilenameUtils工具类
- PowerDesigner(四)-业务处理模型
- (OK) codeblocks-16.01 in docker container [ztg/cbpm]
- ZOJ
- Aop之AspectJ
- yum与apt-get使用差异
- Java程序员必须知道的10个调试技巧
- Java8:流 学会用流
- PowerDesigner(五)-概念数据模型(CDM生成LDM,PDM和OOM)
- 扩增子分析解读7物种分类统计,筛选进化树和其它
- PowerDesigner(六)-物理数据模型(PDM逆向工程)
- H5技术完美实现调用手机摄像头、相册。图片上传base64,图片压缩、预览、删除以及图片旋转90度的处理--demo。
- sql injection 类型总结