好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

在Spring Boot框架中使用AOP的正确姿势

前言

spring boot是基于spring的用来开发web应用的 框架 ,功能与spring mvc有点类似,但是spring boot的一大特点就是需要的配置非常少。spring boot推荐convention over configuration,也就是约定大于配置,因此spring boot会帮你做许多自动的配置,并且spring boot使用的是java config,几乎可以做到零xml文件配置。

假设现在有这样一种场景,需要统计某个接口的处理耗时,我们可以使用aop来实现,aop为aspect oriented programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。在spring boot中使用aop也非常简单,只需要一点简单的配置即可。

需要使用aop的类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@restcontroller

public class downloadcontroller {

 

  @autowired

  private xmldownloadservice downloadservice;

 

  @autowired

  private xmlfileclearservice clearservice;

 

  @requestmapping ( "/download" )

  @timer

  public string download() throws exception {

   downloadservice.download();

   clearservice.compress();

   clearservice.clearall();

   return "ok" ;

  }

}

这是一个使用@restcontroller注解的controller类,这个类会去下载一些xml文件,然后压缩,最后删除下载的xml文件。现在我们要统计整个处理过程的耗时,使用aop来实现。在download上使用了一个@timer注解,这是一个自定义的普通注解,用来标记这个方法作为一个切点。

aspect类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

@aspect

@component

public class vipaspect {

 

  private static final logger logger = loggerfactory.getlogger(vipaspect. class );

 

  private long start;

 

  //定义切点

  @pointcut ( "@annotation(cn.magicwindow.mlink.content.annotation.timer)" )

  public void timer(){}

 

  //在方法执行前执行

  @before ( "timer()" )

  public void before() {

   start = system.currenttimemillis();

  }

 

  //在方法执行后执行

  @after ( "timer()" )

  public void after() {

   long now = system.currenttimemillis();

   logger.info( "job took time {}s in summary" , (now - start) / 1000 );

  }

}

这里使用了注解来标记切点,也可以直接按照方法名称来定义,具体的使用方法可以参考官方文档。

配置spring boot支持aop

?

1

2

3

4

@configuration

@enableaspectjautoproxy

public class config {

}

只需要使用@enableaspectjautoproxy注解开启spring boot的aop支持即可。

最后,在调用download方法之后就会打印出本次处理的用时。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

原文链接:https://juejin.im/post/5b67b8a5f265da0f742f07f1

查看更多关于在Spring Boot框架中使用AOP的正确姿势的详细内容...

  阅读:45次