阅读 147

AOP面向切面编程

AOP面向切面编程

一、什么是AOP

面向切面编程,是利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

可以不通过修改源代码方式,在主干功能里面添加新功能。

二、AOP底层实现原理

AOP底层使用动态代理

第一种:有接口的情况,使用 JDK 动态代理。创建接口实现类代理对象,增强类的方法。



//创建接口,定义方法

public interface UserDao {


    public int add(int a, int b);

    public String update(String id);

}

1

2

3

4

5

6

//创建接口实现类,实现方法

public class UserDaoImpl implements UserDao {

    @Override

    public int add(int a, int b) {

        return a+b;

    }


    @Override

    public String update(String id) {

        return id;

    }

}

1

2

3

4

5

6

7

8

9

10

11

12

使用 Proxy 类里面的newProxyInstance 方法创建代理对象


public class JDKProxy {


    public static void main(String[] args) {

        //创建接口实现类代理对象


        Class[] interfaces = {UserDao.class};


        UserDaoImpl userDaoImpl = new UserDaoImpl();


        /**

         * 第一参数,类加载器

         * 第二参数,增强方法所在的类,这个类实现的接口,支持多个接口

         * 第三参数,实现这个接口 InvocationHandler,创建代理对象,写增强的部分

         */

        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDaoImpl));

        int result = dao.add(1, 2);

        System.out.println("result:" + result);


    }

}


class UserDaoProxy implements InvocationHandler{


    //通过有参构造器,传入被代理对象,实现对原有对象的逻辑增强

    private Object object;

    public UserDaoProxy(Object o){

        this.object = o;

    }


    //实现增强的逻辑

    @Override

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {


        //方法之前

        System.out.println("方法之前执行:" + method.getName() + ",传递的参数为:" + Arrays.toString(args));


        //执行原有的需要被增强的方法

        Object result = method.invoke(object, args);


        //方法之后

        System.out.println("方法之后执行" + object);


        

        return result;

    }

}


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

第二种:没有接口的情况,使用 CGLIB 动态代理。创建子类的代理对象,增强类的方法。




三、AOP的术语

1、连接点

类中可以被增强的方法被称为连接点


2、切入点

实际上真正被实现增强的方法称为切入点


3、通知(增强)

实际增强的逻辑部分称为通知。


通知有多种类型:


前置通知

后置通知

环绕通知

异常通知

最终通知

4、切面

把通知应用到切入点的过程称为切面


这四个术语综合在一起可以理解为:我们可以在所有连接点中,选择一个或者多个切入点,去实现增强的过程叫做切面。


四、AspectJ注解

Spring框架一般都是基于AspectJ实现AOP操作,AspectJ不是Spring组成部分,而是一个独立的AOP框架,一般把AspectJ和Spring框架一起使用来实现AOP操作。


1、切入点表达式

切入点表达式作用是指明对哪个类里面的哪个方法进行增强


语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]) )


例如:对AspectJ.UserDao类里面的add()方法进行增强


execution(* AspectJ.UserDao.add(..))

1

例如:对AspectJ.UserDao类里面的所有方法进行增强


execution(* AspectJ.UserDao.*(..))

1

例如:对AspectJ包里面的所有类的所有方法进行增强


execution(* AspectJ.*.*(..))

1

2、基于AspectJ实现AOP操作

基于xml配置文件实现

创建两个类,一个增强类和一个被增强类,并创建方法

public class Book {


    public void buy(){

        System.out.println("buy()...");

    }

}

1

2

3

4

5

6

public class BookProxy {


    public void before(){

        System.out.println("before()...");

    }

}

1

2

3

4

5

6

在 spring 配置文件中创建两个类对象


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

 

    <!--创建对象-->

    <bean id="book" class="AOPXML.Book"></bean>

    <bean id="bookProxy" class="AOPXML.BookProxy"></bean>

    

</beans>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

在 spring 配置文件中配置切入点


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--创建对象-->

    <bean id="book" class="AOPXML.Book"></bean>

    <bean id="bookProxy" class="AOPXML.BookProxy"></bean>

    

    <!--配置AOP的增强-->

    <aop:config>

        <!--切入点-->

        <aop:pointcut id="pointcut1" expression="execution(* AOPXML.Book.buy())"/>

        

        <!--配置切面-->

        <aop:aspect ref="bookProxy">

            <!--把增强方法作用在具体的切入点上-->

            <aop:before method="before" pointcut-ref="pointcut1"/>  

            

        </aop:aspect>

        

    </aop:config>


</beans>

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

基于注解方式实现

创建一个被增强类,在类里面定义方法


public class User {

    

    public void add(){

        System.out.println("add()方法");

    }

}

1

2

3

4

5

6

创建增强类,编写增强逻辑,类里面创建方法,不同的方法代表不同的通知类型


public class UserProxy {


    //前置通知

    public void before(){

        System.out.println("before()...");

    }

}


1

2

3

4

5

6

7

8

配置通知。在Spring配置文件中开启注解扫描,然后使用注解创建User和UserProxy对象,然后在增强类上面添加注解@Aspect,最后再Spring配置文件中开启生成代理对象。


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    

    <!--开启注解扫描-->

    <context:component-scan base-package="AOPAnnotation"></context:component-scan>

    

    <!--开启Aspect生成代理对象-->

    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@Component

public class User {


    public void add(){

        System.out.println("add()方法");

    }

}


1

2

3

4

5

6

7

8

@Component

@Aspect

public class UserProxy {


    //前置通知

    public void before(){

        System.out.println("before()...");

    }

}

1

2

3

4

5

6

7

8

9

配置不同类型的通知。在增强类里面的作为通知方法的上面添加通知类型注解,实用切入点表达式配置


@Component

@Aspect

public class UserProxy {


    //前置通知

    //@Before注解表示作为前置通知,切入点表达式表示需要增强哪个包下的哪个类的哪个方法

    @Before(value = "execution(* AOPAnnotation.User.add(..))")

    public void before(){

        System.out.println("before()...");

    }

    

    //最终通知,After是在方法之后执行,不管有没有异常都会执行,相当于finally

    @After(value = "execution(* AOPAnnotation.User.add(..))")

    public void after(){

        System.out.println("after()...");

    }

    

    //后置通知,AfterReturning是在返回值之后才执行,有异常则不会执行

    @AfterReturning(value = "execution(* AOPAnnotation.User.add(..))")

    public void afterReturning(){

        System.out.println("afterReturning()...");

    }


    //异常通知

    @AfterThrowing(value = "execution(* AOPAnnotation.User.add(..))")

    public void afterThrowing(){

        System.out.println("afterThrowing()...");

    }



    //环绕通知

    @Around(value = "execution(* AOPAnnotation.User.add(..))")

    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        System.out.println("环绕之前...");

        

        //执行被增强的方法

        proceedingJoinPoint.proceed();

        

        System.out.println("环绕之后...");

    }

}

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

输出结果:


如果有异常


为了简化代码,还可以对抽取出相同的切入点


    //抽取相同的切入点

    @Pointcut(value = "execution(* AOPAnnotation.User.add(..))")

    public void samePointCut(){

        

    }


    //前置通知

    //@Before注解表示作为前置通知,切入点表达式表示需要增强哪个包下的哪个类的哪个方法

    @Before(value = "samePointCut()")

    public void before(){

        System.out.println("before()...");

    }

1

2

3

4

5

6

7

8

9

10

11

12

如果有多个增强类对同一个方法进行增强,可以设置增强类先后执行的优先级


在增强类上面添加注解@Order(数字类型值),数字类型值越小优先级越高


@Component

@Aspect

@Order(3)

public class UserProxy {

...

}

1

2

3

4

5

6

为了实现完全注解开发,可以使用配置类来替换XML配置文件


@Configuration

@ComponentScan(basePackages = {"com.atguigu"})

@EnableAspectJAutoProxy(proxyTargetClass = true)

public class ConfigAop {

}

————————————————

版权声明:本文为CSDN博主「煎丶包」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/qq_39794062/article/details/116140049


文章分类
后端
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐