Spring Aop 应用(一):@Around @Before @After

在使用Spring框架开发中,我们经常会用到Spring Aop(具体什么是Aop可自行百度),下面我们看下它在代码中的作用吧。

创建AopServiceImpl
在创建AopServiceImpl之前我们先了解两个相关注解

@Aspect

放在类名上面,把当前类标识为一个切面供容器读取

@Pointcut

切入点,此注解放在方法上面,指向需要使用的切面编程的方法。此注解下面的方法并不会执行

@Aspect
@Component
public class AopServiceImpl {

    @Pointcut("execution(* com.aop.aop.controller..*(..))")
    public void record(){
        System.out.println("hahahha");
    }

    @Before("record()")
    public void before(){
        System.out.println("before................");
    }

    @After("record()")
    public void after(){
        System.out.println("after.................");
    }

    @Around("record()")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("around before............");
        joinPoint.proceed(); //执行完成目标方法
        System.out.println("around after..............");

    }

创建SysController

@Controller
public class SysController {

    @GetMapping("/sayHello")
    @ResponseBody
    public String sayHello(){
        System.out.println("执行结果................hello");
        return "hello";
    }

执行sayHellof返回结果

around before............
before................
执行结果................hello
around after..............
after.................

可以看出@Before是在方法执行前执行,@After在方法执行后执行,@Around环绕执行,可以再方法执行前后操作。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 本文是我自己在秋招复习时的读书笔记,整理的知识点,也是为了防止忘记,尊重劳动成果,转载注明出处哦!如果你也喜欢,那...
    波波波先森阅读 12,466评论 6 86
  • 本章内容: 面向切面编程的基本原理 通过POJO创建切面 使用@AspectJ注解 为AspectJ切面注入依赖 ...
    谢随安阅读 3,439评论 0 9
  • 因为工作需求,自己去了解一下aop并做下的记录,当然大部分都是参考他人博客以及官方文档。 目录 [关于 AOP](...
    forip阅读 2,386评论 1 20
  • IoC 容器 Bean 的作用域 自定义作用域实现 org.springframework.beans.facto...
    Hsinwong阅读 2,616评论 0 7
  • 睡觉前心情不好的时候,是不应该打电话的。这么久了,觉得自己也深谙此理了。 想写一点东西,不是为了给你看,而是觉得自...
    juliner阅读 264评论 0 0

友情链接更多精彩内容