好得很程序员自学网

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

SpringBoot Aop 详解和多种使用场景解析

前言

aop面向切面编程,是编程中一个很重要的思想本篇文章主要介绍的是springboot切面aop的使用和案例

什么是aop

aop(aspect orientedprogramming):面向切面编程,面向切面编程(也叫面向方面编程),是目前软件开发中的一个热点,也是spring框架中的一个重要内容。利用aop可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

使用场景

利用aop可以对我们边缘业务进行隔离,降低无关业务逻辑耦合性。提高程序的可重用性,同时提高了开发的效率。一般用于 日志记录,性能统计,安全控制,权限管理,事务处理,异常处理,资源池管理 。使用场景

为什么需要面向切面编程

面向对象编程(oop)的好处是显而易见的,缺点也同样明显。当需要为多个不具有继承关系的对象添加一个公共的方法的时候,例如日志记录、性能监控等,如果采用面向对象编程的方法,需要在每个对象里面都添加相同的方法,这样就产生了较大的重复工作量和大量的重复代码,不利于维护。面向切面编程(aop)是面向对象编程的补充,简单来说就是统一处理某一[切面]的问题的编程思想。如果使用aop的方式进行日志的记录和处理,所有的日志代码都集中于一处,不需要再每个方法里面都去添加,极大减少了重复代码。

技术要点

通知(advice)包含了需要用于多个应用对象的横切行为,完全听不懂,没关系,通俗一点说就是定义了[什么时候]和[做什么]。 连接点(join point)是程序执行过程中能够应用通知的所有点。 切点(poincut)是定义了在[什么地方]进行切入,哪些连接点会得到通知。显然,切点一定是连接点。 切面(aspect)是通知和切点的结合。通知和切点共同定义了切面的全部内容——是什么,何时,何地完成功能。 引入(introduction)允许我们向现有的类中添加新方法或者属性。 织入(weaving)是把切面应用到目标对象并创建新的代理对象的过程,分为编译期织入、类加载期织入和运行期织入。

整合使用

导入依赖

在springboot中使用aop要导aop依赖

?

1

2

3

4

5

<!--aop 切面-->

        <dependency>

            <groupid>org.springframework.boot</groupid>

            <artifactid>spring-boot-starter-aop</artifactid>

        </dependency>

注意这里版本依赖于 spring-boot-start-parent 父pom中的 spring-boot-dependencies

编写拦截的bean

这里我们定义一个 controller 用于拦截所有请求的记录

?

1

2

3

4

5

6

7

8

9

@restcontroller

public class aopcontroller {

 

     @requestmapping ( "/hello" )

     public string sayhello(){

         system.out.println( "hello" );

         return "hello" ;

     }

}

定义切面

springboot在使用切面的时候采用 @aspect 注解对pojo进行标注,该注解表明该类不仅仅是一个pojo,还是一个切面容器

定义切点

切点是通过 @pointcut 注解和 切点表达式 定义的。

@pointcut注解可以在一个切面内定义可 重用 的切点。

由于spring切面粒度最小是达到 方法级别 ,而 execution表达式 可以用于明确指定方法返回类型,类名,方法名和参数名等与方法相关的部件,并且实际中,大部分需要使用aop的业务场景也只需要达到方法级别即可,因而execution表达式的使用是最为广泛的。如图是execution表达式的语法:

execution表示在方法执行的时候触发。以[]开头,表明方法返回值类型为任意类型。然后是全限定的类名和方法名,[]可以表示任意类和任意方法。对于方法参数列表,可以使用[..]表示参数为任意类型。如果需要多个表达式,可以使用[&&]、[||]和[!]完成与、或、非的操作。

定义通知

通知有五种类型,分别是:

前置通知(@before):在目标方法调用之前调用通知 后置通知(@after):在目标方法完成之后调用通知 环绕通知(@around):在被通知的方法调用之前和调用之后执行自定义的方法 返回通知(@afterreturning):在目标方法成功执行之后调用通知 异常通知(@afterthrowing):在目标方法抛出异常之后调用通知

代码中定义了三种类型的通知,使用@before注解标识前置通知,打印[beforeadvice...],使用@after注解标识后置通知,打印[afteradvice...],使用@around注解标识环绕通知,在方法执行前和执行之后分别打印[before]和[after]。这样一个切面就定义好了,代码如下:

?

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

26

27

28

29

30

31

@aspect

@component

public class aopadvice {

 

     @pointcut ( "execution (* com.shangguan.aop.controller.*.*(..))" )

     public void test() {

 

     }

 

     @before ( "test()" )

     public void beforeadvice() {

         system.out.println( "beforeadvice..." );

     }

 

     @after ( "test()" )

     public void afteradvice() {

         system.out.println( "afteradvice..." );

     }

 

     @around ( "test()" )

     public void aroundadvice(proceedingjoinpoint proceedingjoinpoint) {

         system.out.println( "before" );

         try {

             proceedingjoinpoint.proceed();

         } catch (throwable t) {

             t.printstacktrace();

         }

         system.out.println( "after" );

     }

 

}

运行结果

案例场景

这里我们通过一个日志记录场景来完整的使用aop切面业务层只需关心代码逻辑实现而不用关心请求参数和响应参数的日志记录

那么首先我们需要自定义一个全局日志记录的切面类 globallogaspect

然后在该类添加@aspect注解,然后在定义一个公共的切入点(pointcut),指向需要处理的包,然后在定义一个前置通知(添加@before注解),后置通知(添加@afterreturning)和环绕通知(添加@around)方法实现即可

日志信息类

?

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

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

package cn.soboys.core;

 

import lombok.data;

 

/**

  * @author kenx

  * @version 1.0

  * @date 2021/6/18 18:48

  * 日志信息

  */

@data

public class logsubject {

     /**

      * 操作描述

      */

     private string description;

 

     /**

      * 操作用户

      */

     private string username;

 

     /**

      * 操作时间

      */

     private string starttime;

 

     /**

      * 消耗时间

      */

     private string spendtime;

 

     /**

      * url

      */

     private string url;

 

     /**

      * 请求类型

      */

     private string method;

 

     /**

      * ip地址

      */

     private string ip;

 

     /**

      * 请求参数

      */

     private object parameter;

 

     /**

      * 请求返回的结果

      */

     private object result;

 

     /**

      * 城市

      */

     private string city;

 

     /**

      * 请求设备信息

      */

     private string device;

 

}

全局日志拦截

?

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

26

27

28

29

30

31

32

33

34

35

36

37

38

package cn.soboys.core;

 

import org.aspectj.lang.proceedingjoinpoint;

import org.aspectj.lang.reflect.methodsignature;

 

import java.lang.reflect.method;

 

/**

  * @author kenx

  * @version 1.0

  * @date 2021/6/18 14:52

  * 切面

  */

public class baseaspectsupport {

     public method resolvemethod(proceedingjoinpoint point) {

         methodsignature signature = (methodsignature)point.getsignature();

         class <?> targetclass = point.gettarget().getclass();

 

         method method = getdeclaredmethod(targetclass, signature.getname(),

                 signature.getmethod().getparametertypes());

         if (method == null ) {

             throw new illegalstateexception( "无法解析目标方法: " + signature.getmethod().getname());

         }

         return method;

     }

 

     private method getdeclaredmethod( class <?> clazz, string name, class <?>... parametertypes) {

         try {

             return clazz.getdeclaredmethod(name, parametertypes);

         } catch (nosuchmethodexception e) {

             class <?> superclass = clazz.getsuperclass();

             if (superclass != null ) {

                 return getdeclaredmethod(superclass, name, parametertypes);

             }

         }

         return null ;

     }

}

globallogaspect 类

?

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

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

package cn.soboys.core;

 

import cn.hutool.core.date.dateutil;

import cn.hutool.core.date.timeinterval;

import cn.hutool.json.jsonutil;

import cn.soboys.core.utils.httpcontextutil;

import io.swagger.annotations.apioperation;

import lombok.extern.slf4j.slf4j;

import org.aspectj.lang.proceedingjoinpoint;

import org.aspectj.lang.annotation.afterthrowing;

import org.aspectj.lang.annotation.around;

import org.aspectj.lang.annotation.aspect;

import org.aspectj.lang.annotation.pointcut;

import org.springframework.stereotype测试数据ponent;

import org.springframework.web.bind.annotation.requestbody;

import org.springframework.web.bind.annotation.requestparam;

 

import javax.servlet.http.httpservletrequest;

import java.lang.reflect.method;

import java.lang.reflect.parameter;

import java.util.arraylist;

import java.util.hashmap;

import java.util.list;

import java.util.map;

 

/**

  * @author kenx

  * @version 1.0

  * @date 2021/6/18 15:22

  * 全局日志记录器

  */

@slf4j

@aspect

@component

public class globallogaspect extends baseaspectsupport {

     /**

      * 定义切面pointcut

      */

     @pointcut ( "execution(public * cn.soboys.mallapi.controller.*.*(..))" )

     public void log() {

 

     }

 

 

     /**

      * 环绕通知

      *

      * @param joinpoint

      * @return

      */

     @around ( "log()" )

     public object doaround(proceedingjoinpoint joinpoint) throws throwable {

 

         logsubject logsubject = new logsubject();

         //记录时间定时器

         timeinterval timer = dateutil.timer( true );

         //执行结果

         object result = joinpoint.proceed();

         logsubject.setresult(result);

         //执行消耗时间

         string endtime = timer.intervalpretty();

         logsubject.setspendtime(endtime);

         //执行参数

         method method = resolvemethod(joinpoint);

         logsubject.setparameter(getparameter(method, joinpoint.getargs()));

 

         httpservletrequest request = httpcontextutil.getrequest();

         // 接口请求时间

         logsubject.setstarttime(dateutil.now());

         //请求链接

         logsubject.seturl(request.getrequesturl().tostring());

         //请求方法get,post等

         logsubject.setmethod(request.getmethod());

         //请求设备信息

         logsubject.setdevice(httpcontextutil.getdevice());

         //请求地址

         logsubject.setip(httpcontextutil.getipaddr());

         //接口描述

         if (method.isannotationpresent(apioperation. class )) {

             apioperation apioperation = method.getannotation(apioperation. class );

             logsubject.setdescription(apioperation.value());

         }

 

         string a = jsonutil.tojsonprettystr(logsubject);

         log.info(a);

         return result;

 

     }

 

 

     /**

      * 根据方法和传入的参数获取请求参数

      */

     private object getparameter(method method, object[] args) {

         list<object> arglist = new arraylist<>();

         parameter[] parameters = method.getparameters();

         map<string, object> map = new hashmap<>();

         for ( int i = 0 ; i < parameters.length; i++) {

             //将requestbody注解修饰的参数作为请求参数

             requestbody requestbody = parameters[i].getannotation(requestbody. class );

             //将requestparam注解修饰的参数作为请求参数

             requestparam requestparam = parameters[i].getannotation(requestparam. class );

             string key = parameters[i].getname();

             if (requestbody != null ) {

                 arglist.add(args[i]);

             } else if (requestparam != null ) {

                 map.put(key, args[i]);

             } else {

                 map.put(key, args[i]);

             }

         }

         if (map.size() > 0 ) {

             arglist.add(map);

         }

         if (arglist.size() == 0 ) {

             return null ;

         } else if (arglist.size() == 1 ) {

             return arglist.get( 0 );

         } else {

             return arglist;

         }

     }

}

到此这篇关于springboot aop 详解和多种使用场景的文章就介绍到这了,更多相关springboot aop使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://HdhCmsTestcnblogs测试数据/kenx/p/15088701.html

查看更多关于SpringBoot Aop 详解和多种使用场景解析的详细内容...

  阅读:13次