0
点赞
收藏
分享

微信扫一扫

Springboot-aop的使用

上善若水山西太原 2023-11-15 阅读 41

aop:面向切面编程,可以看作是面向对象的补充
举例
在这里插入图片描述

1.依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--引入AOP依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.28</version>
    </dependency>
    </dependencies>

2.使用

1.自定义注解

/**
 * @author wyr
 * @version 1.0
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
    /**
     * 描述
     *
     * @return {String}
     */
    String value() default "";
}

2.切面类

@Slf4j
@Aspect
@Component
public class SysLogAspect {
    //定义切点 值为注解的全路径 拦截所有使用了拦截SysLog注解的方法
    @Pointcut("@annotation(com.example.demo.annotation.SysLog)")
    public void sysLogAspect() {

    }
    @Around(value="sysLogAspect()") //直接value="@annotation(com.example.demo.annotation.SysLog)"也可以
    public Object around(ProceedingJoinPoint point){
        Object proceed = null;
        try {
            //使用注解的方法执行之前 相等于 @before
            //获取类名
            String className = point.getTarget().getClass().getName();
            //获取执行的方法名
            String methodName = point.getSignature().getName();
            //获取参数
            Object[] args = point.getArgs();
            //获取方法上注解的值
            MethodSignature methodSignature = (MethodSignature)point.getSignature();
            String annotationVal= methodSignature.getMethod().getAnnotation(SysLog.class).value();

            log.info("[类名]:{},[方法]:{},[参数]:{},[操作]:{}", className, methodName, JSON.toJSONString(args),annotationVal);
            //相等于放行 如果直接return 则不执行使用了该注解对应的方法
            System.out.println("方法执行之前");
            proceed = point.proceed();
            System.out.println("方法执行之后");
            //使用注解的方法之后
            System.out.println("方法的返回值是:"+proceed);

        } catch (Throwable e) {
            throw  new RuntimeException(e.getMessage());
        }
        return proceed;
    }

}

3.使用

@RestController
public class UserController {
    @GetMapping("/test/{name}")
    @SysLog("操作是获取名称")
    public String test(@PathVariable("name") String name){
        System.out.println("方法开始执行");
        return "我是返回值";
    }
}
举报

相关推荐

0 条评论