46_springboot的自定义注解简单使用

通过自定义注解,可以轻松在方法或者类执行时去前置执行各种想要的方法

先导入pom坐标

 <!-- AOP依赖模块 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
<!-- web依赖相关 -->
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

1.先定义自定义注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
    String module() default "";

}

2.准备完整服务链 controller层,service层

@RestController
public class HelloWorldController {

   @Autowired
    private SysLogService helloWorldService;

    @LogAnnotation
    @RequestMapping(value = "/info3", method = RequestMethod.GET)
    public void hello() {
      System.out.println("进入controll层");
        helloWorldService.save();
        System.out.println("controller层save方法执行完毕...");
    }

}

@Service
public class SysLogServiceImpl implements SysLogService {
//中间接口就不贴上来了
   

    @Override
    public void save() {
        System.out.println("执行了impl_save方法");
    }

    @Override
    public void myInterface() {
        System.out.println("执行了impl_myInterface方法");
    }




}

3.定义切面


@Aspect
@Component
public class LogAdvice {

    @Autowired
    private SysLogService sysLogService;

    @Around(value = "@annotation(LogAnnotation)")
    public Object logSave(ProceedingJoinPoint joinPoint) throws Throwable {
       

 System.out.println("进入到切点处理方法");
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        System.out.println("切点执行1");
        LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class);
        System.out.println("切点执行2");
            Object object = joinPoint.proceed();
            System.out.println("切点执行3");
            sysLogService.myInterface();
            System.out.println("切点执行4");


}
}

例如设置端口是8099的话,启动访问
http://localhost:8089/info3
得到如下结果

image.png

后续待补充,感觉这个是比较简单的实例了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,971评论 6 342
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,590评论 1 92
  • 前天晚上我失眠了,在我身上失眠偶尔发生几次也是正常的,因为我的入睡时间比较长了。 第二天我告诉他我昨天失眠了,快两...
    啾啾啾一吖阅读 181评论 0 0
  • 人活着就一定要活的精彩,不论遇到什么事情,都要保持好的心态。 自从姥爷去世,姥姥就孤单一人。每天大部分时间就是和一...
    k坚持阅读 134评论 2 1