spring学习笔记(三)3. Spring核心之AOP

3 Spring核心之AOP

3.1 什么是AOP

AOP为Aspect Oriented Programming的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

AOP的作用:不修改源码的情况下,程序运行期间对方法进行功能增强

好处:1、减少代码的重复,提高开发效率,便于维护。

​ 2、专注核心业务的开发。

核心业务和服务性代码混合在一起

开发中:各自做自己擅长的事情,运行的时候将服务性代码织入到核心业务中。

通过spring工厂自动实现将服务性代码以切面的方式加入到核心业务代码中。

3.2 代理模式

3.2.1 什么是代理模式

代理:自己不做,找人帮你做。

代理模式:在一个原有功能的基础上添加新的功能。

分类:静态代理和动态代理。

AOP的实现机制-动态代理

3.2.2 静态代理

3.2.2.1 原有方式

核心业务和服务方法都编写一起

public class TeamService {
	public void add(){
        try {
            System.out.println("开始事务");
            System.out.println("TeamService---- add----");// 核心业务
            System.out.println("提交事务");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("回滚事务");
        }
    }
}
3.2.2.2 基于类的静态代理

将服务性代码分离出来,核心业务–保存业务中只有保存功能

核心业务:

public class TeamService {
	public void add(){
        System.out.println("TeamService---- add----");// 核心业务
    }
}

静态代理:

/**
 * 基于类的静态代理的类
 *  要求集成被代理的类
 *  弊端:每次只能代理一个类
 */
public class ProxyTeamService extends TeamService {
    @Override
    public void add() {
        try {
            System.out.println("开始事务");
            super.add();//核心业务就是由被代理对象完成,其他事务功能由代理类完成
        }catch (Exception e){
            System.out.println("事务回滚");
        }
    }
}

测试:

public static void main(String[] args) {
    TeamService service=new ProxyTeamService();
    service.add();
}

弊端:代理类只能代理一个类

3.2.2.3 基于接口的静态代理

为核心业务(保存add)创建一个接口,通过接口暴露被代理的方法

要求:代理类和被代理类都实现了同一个接口

接口:

public interface IService {
    void add();
}

业务:

package com.zisen.service;

public class TeamService implements IService {
    @Override
    public void add(){
        System.out.println("TeamService---add()");
    }

}

事务代理:

package com.zisen.service.staticproxy;
import com.zisen.service.IService;

/**
 * 基于接口的静态代理
 * 代理类和被代理类实现同一个接口
 */
public class ProxyTranService implements IService {
    private IService service;

    public ProxyTranService(IService service) {
        this.service = service;
    }

    @Override
    public void add() {
        try {
            System.out.println("开始事务");
            service.add();//核心业务就是由被代理对象完成 ;其他服务功能由代理类完成
            System.out.println("提交事务");
        }catch (Exception e){
            System.out.println("事务回滚");
        }
    }
}

日志代理:

package com.zisen.service.staticproxy;

import com.zisen.service.IService;

public class ProxyLogService implements IService {
    private IService service;

    public ProxyLogService(IService service) {
        this.service = service;
    }

    @Override
    public void add() {
        try {
            System.out.println("开始日志");
            service.add();//核心业务就是由被代理对象完成 ;其他服务功能由代理类完成
            System.out.println("提交日志");
        } catch (Exception e) {
            System.out.println("异常日志");
        }
    }
}

测试类:

package com.zisen.test;

import com.zisen.service.TeamService;

import com.zisen.service.staticproxy.ProxyLogService;
import com.zisen.service.staticproxy.ProxyTranService;

public class Test01 {
    public static void main(String[] args) {
        TeamService teamService=new TeamService();//被代理对象
        ProxyTranService tranService=new ProxyTranService(teamService);//事务代理对象--一级代理
        ProxyLogService logService=new ProxyLogService(tranService);//日志代理对象--二级代理
        logService.add();
    }
}
3.2.2.4 提取出切面代理,作为AOP接口

共有4个位置可以将切面代码编织进入核心业务代码中。

接口:

package com.zisen.aop;

/**
 * 切面:服务代码,切入到核心代码中,切入到哪里,给了四个位置
 */
public interface AOP {
    void before();
    void after();
    void exception();
    void myFinally();
}

事务AOP:

package com.zisen.aop.impl;

import com.zisen.aop.AOP;

public class TranAop implements AOP {
    @Override
    public void before() {
        System.out.println("事务---before()");
    }

    @Override
    public void after() {
        System.out.println("事务---after()");
    }

    @Override
    public void exception() {
        System.out.println("事务---exception()");
    }

    @Override
    public void myFinally() {
        System.out.println("事务---myFinally()");
    }
}

日志AOP:

package com.zisen.aop.impl;

import com.zisen.aop.AOP;

public class LogAop implements AOP {
    @Override
    public void before() {
        System.out.println("日志---before()");
    }

    @Override
    public void after() {
        System.out.println("日志---after()");
    }

    @Override
    public void exception() {
        System.out.println("日志---exception()");
    }

    @Override
    public void myFinally() {
        System.out.println("日志---myFinally()");
    }
}

服务:

package com.zisen.service.staticproxy;

import com.zisen.aop.AOP;
import com.zisen.service.IService;

public class ProxyAopService implements IService {
    private IService service;//被代理的对象
    private AOP aop;//要加入的切面

    public ProxyAopService(IService service, AOP aop) {
        this.service = service;
        this.aop = aop;
    }

    @Override
    public void add() {
        try {
            aop.before();
            service.add();
            aop.after();
        }catch (Exception e){
            aop.exception();
        }finally {
            aop.myFinally();
        }
    }
}

测试:

@Test
public void test01(){
    TeamService teamService=new TeamService();//被代理的对象
    AOP logAop=new LogAop();//切面--日记服务性内容
    AOP tranAop =new TranAop();//切面--事务服务性内容
    IService service=new ProxyAopService(teamService, logAop);//代理对象--一级代理
    IService service2=new ProxyAopService(service,tranAop);//代理对象--二级代理
    service2.add();
}

总结静态代理:

1)可以做到在不修改目标对象的功能前提下,对目标对象功能扩展。

2)缺点:

因为代理对象,需要与目标对象实现一样的接口。所以会有很多代理类,类太多。

一旦接口增加方法,目标对象与代理对象都要维护。

3.2.3 动态代理

静态代理:要求代理类一定存在。

动态代理:程序运行的时候,根据要被代理的对象动态生成代理类。

类型:1、基于JDK的动态代理

​ 2、基于CGLIB的动态代理

3.2.3.1 基于JDK的动态代理

在这里插入图片描述

3.2.3.1.1 测试类
/*newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandlerh)
ClassLoader :类加载器,因为动态代理类,借助别人的类加载器。一般使用被代理对象的类加载器。
Class<?>[] interfaces:接口类对象的集合,针对接口的代理,针对哪个接口做代理,一般使用的就是被代理对象的接口。
InvocationHandler:句柄,回调函数,编写代理的规则代码

public Object invoke(Object arg0, Method arg1, Object[] arg2)
Object arg0:代理对象
Method arg1:被代理的方法
Object[] arg2:被代理方法被执行的时候的参数的数组
*/
package com.zisen.dynamicproxy;

import com.zisen.service.IService;
import com.zisen.service.TeamService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyJDKProxy {
    public static void main(String[] args) {
        //目标对象-被代理对象
        final TeamService teamService=new TeamService();
        //返回代理对象,基于JDK的动态代理
        IService proxyService= (IService) Proxy.newProxyInstance(
                teamService.getClass().getClassLoader(),
                teamService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try {
                            System.out.println("开始事务");
                            Object invoke = method.invoke(teamService, args);//核心方法
                            System.out.println("提交事务");
                            return invoke;
                        }catch (Exception e){
                            System.out.println("事务回滚");
                            e.printStackTrace();
                            throw e;
                        }finally {
                            System.out.println("finally----");
                        }
                    }
                }
        );
        //代理对象干活
        proxyService.add();
    }
}
3.2.3.1.2 结构化设计

方式1,提取单独MyJDKProxy.java:

package com.zisen.dynamicproxy;

import com.zisen.aop.AOP;
import com.zisen.service.IService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class ProxyHandler implements InvocationHandler {
    private IService service;//目标对象
    private AOP aop;//切面
    public ProxyHandler(IService service, AOP aop) {
        this.service = service;
        this.aop = aop;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            aop.before();
            Object invoke = method.invoke(service, args);//核心方法
            aop.after();
            return invoke;
        }catch (Exception e){
            aop.exception();
            e.printStackTrace();
            throw e;
        }finally {
            aop.myFinally();
        }
    }
}

测试类:

package com.zisen.dynamicproxy;

import com.zisen.aop.AOP;
import com.zisen.aop.impl.TranAop;
import com.zisen.service.IService;
import com.zisen.service.TeamService;

import java.lang.reflect.Proxy;

public class MyJDKProxy {
    public static void main(String[] args) {
        //目标对象-被代理对象
        TeamService teamService=new TeamService();
        //切面
        AOP tranAop=new TranAop();
        //返回代理对象,基于JDK的动态代理
        IService proxyService= (IService) Proxy.newProxyInstance(
                teamService.getClass().getClassLoader(),
                teamService.getClass().getInterfaces(),
                new ProxyHandler(teamService,tranAop)
        );
        //代理对象干活
        proxyService.add();
        System.out.println(teamService.getClass());
        System.out.println(proxyService.getClass());
    }
}

方式2,提取ProxyFactory.java

package com.zisen.dynamicproxy;

import com.zisen.aop.AOP;
import com.zisen.service.IService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory {
    private IService service;//目标对象
    private AOP aop;//切面

    public ProxyFactory(IService service, AOP aop) {
        this.service = service;
        this.aop = aop;
    }

    /**
     * 获取动态代理的实例
     * @return
     */
    public Object getProxyInstance(){
        return Proxy.newProxyInstance(
                service.getClass().getClassLoader(),
                service.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try {
                            aop.before();
                            Object invoke = method.invoke(service, args);//核心方法
                            aop.after();
                            return invoke;
                        }catch (Exception e){
                            aop.exception();
                            e.printStackTrace();
                            throw e;
                        }finally {
                            aop.myFinally();
                        }
                    }
                }
        );
    }
}

测试类:

package com.zisen.dynamicproxy;

import com.zisen.aop.AOP;
import com.zisen.aop.impl.LogAop;
import com.zisen.aop.impl.TranAop;
import com.zisen.service.IService;
import com.zisen.service.TeamService;

import java.lang.reflect.Proxy;

public class MyJDKProxy {
    public static void main(String[] args) {
        //目标对象-被代理对象
        TeamService teamService=new TeamService();
        //切面
        AOP tranAop=new TranAop();
        AOP logAop=new LogAop();

        //获取代理对象
        IService service= (IService) new ProxyFactory(teamService, tranAop).getProxyInstance();
        IService service1= (IService) new ProxyFactory(service, logAop).getProxyInstance();
        service1.add();//核心业务+服务代码混合在一起的完整的业务方法
    }
}

代理对象不需要实现接口,但是目标对象一定要实现接口;否则不能用JDK动态代理

如果想要功能扩展,但目标对象没有实现接口,怎样功能扩展?

子类的方式实现代理CGLIB 。

3.2.3.2 基于CGLIB的动态代理

CGLIB代理,也叫做子类代理。在内存中构建一个子类对象从而实现对目标对象功能的扩展。

  • JDK的动态代理有一个限制,就是使用动态代理的对象必须实现一个或多个接口。如果想代理没有实现接口的类,就可以使用CGLIB实现。
  • CGLIB是一个强大的高性能的代码生成包,它可以在运行期扩展Java类与实现Java接口。它广泛的被许多AOP的框架使用,例如Spring AOP和dynaop,为他们提供方法的interception。
  • CGLIB包的底层是通过使用一个小而快的字节码处理框架ASM,来转换字节码并生成新的类。不鼓励直接使用ASM,因为它要求你必须对JVM内部结构包括class文件的格式和指令集都很熟悉。
3.2.3.2.1 依赖
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.3.0</version>
</dependency>

无接口的NBAService.java:

package com.zisen.cglibproxy;

public class NBAService {

    public void add(){
        System.out.println("NBAService---add");
    }
}

测试类:

package com.zisen.cglibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyCglibProxy {
    public static void main(String[] args) {
        //目标对象,没有接口
        NBAService nbaService=new NBAService();
        //创建代理对象,选择cglib动态代理
        NBAService proxyService= (NBAService) Enhancer.create(nbaService.getClass(),
                new MethodInterceptor() {//回调函数编写规则
                    @Override
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        try {
                            System.out.println("开始事务");
                            Object invoke = methodProxy.invokeSuper(o, objects);//核心
                            System.out.println("提交事务");
                            return invoke;
                        }catch (Exception e){
                            e.printStackTrace();
                            System.out.println("事务回滚");
                            throw e;
                        }finally {
                            System.out.println("finally----");
                        }
                    }
                });
        proxyService.add();
    }
}
3.2.3.2.2 结构化设计方式

创建代理对象类:

package com.zisen.cglibproxy;

import com.zisen.aop.AOP;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxyFactory {
    //目标对象
    private NBAService nbaService;//没有实现接口的
    //切面
    AOP aop;

    public CglibProxyFactory(NBAService nbaService, AOP aop) {
        this.nbaService = nbaService;
        this.aop = aop;
    }

    /**
     * 创建代理对象
     * @return
     */
    public Object getProxyInstance(){
        return Enhancer.create(nbaService.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                try {
                    aop.before();
                    Object invoke = methodProxy.invokeSuper(o, objects);
                    aop.after();
                    return invoke;
                } catch (Exception e) {
                    aop.exception();
                    e.printStackTrace();
                    throw e;
                } finally {
                    aop.myFinally();
                }
            }
        });
    }
}

测试:

package com.zisen.cglibproxy;

import com.zisen.aop.AOP;
import com.zisen.aop.impl.TranAop;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyCglibProxy {
    public static void main(String[] args) {
        //目标对象,没有接口
        NBAService nbaService=new NBAService();
        //切面
        AOP tranAop=new TranAop();
        NBAService nbaService1= (NBAService) new CglibProxyFactory(nbaService, tranAop).getProxyInstance();
        nbaService1.add();
    }
   
}

3.3 Spring AOP

3.3.1 Spring AOP相关概念

Spring的AOP实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。

我们先来介绍AOP的相关术语:

  • Target(目标对象)

要被增强的对象,一般是业务逻辑类的对象。

  • Proxy(代理)

一个类被 AOP 织入增强后,就产生一个结果代理类。

  • Aspect(切面)

表示增强的功能,就是一些代码完成的某个功能,非业务功能。是切入点和通知的结合。

  • Joinpoint(连接点)

所谓连接点是指那些被拦截到的点。在Spring中,这些点指的是方法(一般是类中的业务方法),因为
Spring只支持方法类型的连接点。

  • Pointcut(切入点)

切入点指声明的一个或多个连接点的集合。通过切入点指定一组方法。

被标记为 final 的方法是不能作为连接点与切入点的。因为最终的是不能被修改的,不能被增强的。

  • Advice(通知/增强)

所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知。通知定义了增强代码切入到目标代码的时间点,是目标方法执行之前执行,还是之后执行等。通知类型不同,切入时间不同。

通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。

切入点定义切入的位置,通知定义切入的时间。

  • Weaving(织入)

是指把增强应用到目标对象来创建新的代理对象的过程。 spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入。

​ 切面的三个关键因素:

​ 1、切面的功能–切面能干啥

​ 2、切面的执行位置–使用Pointcut表示切面执行的位置

​ 3、切面的执行时间–使用Advice表示时间,在目标方法之前还是之后执行。

3.3.2 AspectJ 对 AOP 的实现

对于 AOP 这种编程思想,很多框架都进行了实现。Spring 就是其中之一,可以完成面向切面编程。

AspectJ 也实现了 AOP 的功能,且其实现方式更为简捷而且还支持注解式开发。所以,Spring 又将
AspectJ 的对于 AOP 的实现也引入到了自己的框架中。

在 Spring 中使用 AOP 开发时,一般使用 AspectJ 的实现方式

​ AspectJ 是一个优秀面向切面的框架,它扩展了 Java 语言,提供了强大的切面实现。

3.3.2.1 AspectJ的通知类型

AspectJ 中常用的通知有5种类型:

  1. 前置通知
  2. 后置通知
  3. 环绕通知
  4. 异常通知
  5. 最终通知
3.3.2.2 AspectJ的切入点表达式
AspectJ 定义了专门的表达式用于指定切入点。
表达式的原型如下:
execution(modifiers-pattern? ret-type-pattern
declaring-type-pattern?name-pattern(param-pattern)
throws-pattern?)
说明:
modifiers-pattern] 访问权限类型
ret-type-pattern 返回值类型
declaring-type-pattern 包名类名
name-pattern(param-pattern) 方法名(参数类型和参数个数)
throws-pattern 抛出异常类型
?表示可选的部分

以上表达式共 4 个部分。

execution(访问权限 方法返回值 方法声明(参数) 异常类型)

切入点表达式要匹配的对象就是目标方法的方法名。所以,execution 表达式中就是方法的签名。

PS:表达式中黑色文字表示可省略部分,各部分间用空格分开。在其中可以使用以下符号:

符号意义
*0-多个任意字符
用在方法参数中,表示任意个参数;用在包名后,表示当前及其子包路径
+用在类名后,表示当前及其子类;用在接口后,表示当前接口及其实现类
示例:
execution(* com.kkb.service.*.*(..))
指定切入点为:定义在 service 包里的任意类的任意方法。
execution(* com.kkb.service..*.*(..))
指定切入点为:定义在 service 包或者子包里的任意类的任意方法。“..”出现在类名中时,后面必须跟“*”,表示包、子包下的所有类。
execution(* com.kkb.service.IUserService+.*(..))
指定切入点为:IUserService 若为接口,则为接口中的任意方法及其所有实现类中的任意方法;若为类,则为该类及其子类中的任意方法。

3.3.3 注解方式实现AOP

开发阶段:关注核心业务和AOP代码

运行阶段:spring框架会在运行的时候将核心业务和AOP代码通过动态代理的方式编织在一起。

代理方式的选择:是否实现了接口:有接口就选择JDK动态代理;没有就选择CGLIB动态代理。

1、创建项目引入依赖

<dependencies>
    <!--spring依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.13.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.2.13.RELEASE</version>
    </dependency>
    <!--单元测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

2、创建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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--在beans标签中引入AOP约束和context约束-->

</beans>

3、创建核心业务类

package com.zisen.service;

public interface IService {
    void add(Integer id,String name);
    boolean update(int num);
}
package com.zisen.service.impl;

import com.zisen.service.IService;

/**
 * 核心业务类
 */
public class TeamServiceImpl implements IService {
    @Override
    public void add(Integer id, String name) {
        System.out.println("TeamServiceImpl---add");
    }

    @Override
    public boolean update(int num) {
        System.out.println("TeamServiceImpl---update");
        return num > 666;
    }
}
package com.zisen.service.impl;

import com.zisen.service.IService;
import org.springframework.stereotype.Service;

/**
 * 核心业务类
 */
@Service("nbaService")
public class NBAService implements IService {
    @Override
    public void add(Integer id, String name) {
        System.out.println("NBAService---add");
    }

    @Override
    public boolean update(int num) {
        System.out.println("NBAService---update");
        return num > 666;
    }
}

4、定义切面类

package com.zisen.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 切面类
 */
@Component //却面对象的创建权限交给spring容器
@Aspect //aspectj框架的注解,标识当前类是一个切面类
public class MyAspect {

    /**
     * 当较多的通知增强方法使用相同的 execution 切入点表达式时,编写、维护均较为麻烦。
     * AspectJ 提供了@Pointcut 注解,用于定义 execution 切入点表达式。
     * 其用法是,将@Pointcut 注解在一个方法之上,以后所有的 execution 的 value 属性值均
     * 可使用该方法名作为切入点。代表的就是@Pointcut 定义的切入点。
     * 这个使用@Pointcut 注解方法一般使用 private 的标识方法,即没有实际作用的方法。
     */
    @Pointcut("execution(* com.zisen.service..*.*(..))")
    private void pointCut(){

    }

    /**
     * 声明前置通知
     * @param joinPoint
     */
    @Before("pointCut()")
    public void before(JoinPoint joinPoint){
        System.out.println("前置通知:在目标方法执行之前被调用的通知。");
        String name = joinPoint.getSignature().getName();
        System.out.println("拦截的方法名称是:"+name);
        Object[] args = joinPoint.getArgs();
        System.out.println("方法的参数格式是:"+args.length);
        for (Object arg : args) {
            System.out.println("\t"+arg);
        }
    }

    /**
     * AfterReturning 注解声明后置通知
     * value:表示切入点表达式
     * returning:表示返回结果,如果需要的话可以在后置通知的方法中修改结果
     * @param result
     */
    @AfterReturning(value = "execution(* com.zisen.service..*.update*(..))",returning = "result")
    public void afterReturning(Object result){
        if(result!=null){
            boolean res=(boolean)result;
            if(res){
                result=false;
            }
        }
        System.out.println("后置通知:在目标方法执行之后被调用的通知。"+result);
    }

    /**
     * Around:注解声明环绕通知
     * ProceedingJoinPoint中的proceed()方法表示目标方法被执行
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.zisen.service..*.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕通知:在目标方法执行之前调用的通知。");
        Object proceed = pjp.proceed();
        System.out.println("环绕通知:在目标方法执行之后调用的通知。");
        return proceed;
    }

    /**
     * AfterThrowing:注解声明异常通知
     * value:表示切入点表达式
     */
    @AfterThrowing(value = "execution(* com.zisen.service..*.add*(..))",throwing = "ex")
    public void exception(JoinPoint jp,Throwable ex){
        //一般会把异常发生的时间,位置,原因都记录下来
        System.out.println("异常通知:在目标方法执行出现异常时被调用的通知。");
        System.out.println(jp.getSignature()+"方法出现异常,异常信息 :"+ex.getMessage());
    }

    /**
     * After:注解声明最终通知
     */
    @After("execution(* com.zisen.service..*.*(..))")
    public void myFinally(){
        System.out.println("最终通知:无论是否出现异常,最终都会被调用的通知。");
    }

}

5、业务类和切面类添加注解

业务类:
在这里插入图片描述
在这里插入图片描述
切面类:
在这里插入图片描述

在定义好切面 Aspect 后,需要通知 Spring 容器,让容器生成“目标类+ 切面”的代理对象。这个代理是由容器自动生成的。只需要在 Spring 配置文件中注册一个基于 AspectJ 的自动代理生成器,其就会自动扫描到@Aspect 注解,并按通知类型与切入点,将其织入,并生成代理。

6、spring.xml配置文件中开启包扫描和 注册aspectj的自动代理

<!--包扫描-->
<context:component-scan base-package="com.zisen.service,com.zisen.aop"/>
<!--开启注解AOP的使用-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!--aop:aspectj-autoproxy的底层是由 AnnotationAwareAspectJAutoProxyCreator 实现的,是基于 AspectJ 的注解适配自动代理生成器。
其工作原理是,aop:aspectj-autoproxy通过扫描找到@Aspect 定义的切面类,再由切面类根据切入点找到目标类的目标方法,再由通知类型找到切入的时间点。-->

7、测试类:

package com.zisen.text;


import com.zisen.service.impl.NBAService;
import com.zisen.service.impl.TeamService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test01 {

    @Test
    public void test01(){
        ApplicationContext ac=new ClassPathXmlApplicationContext("spring.xml");
        TeamService teamService = (TeamService) ac.getBean("teamService");
        teamService.add(1, "a");
        System.out.println("-------");
        boolean update = teamService.update(888);
        System.out.println(update);

        System.out.println("==================");
        NBAService nbaService = (NBAService) ac.getBean("nbaService");
        nbaService.add(02, "aaa");
        System.out.println("-------");
        nbaService.update(222);
    }
}

3.3.4 XML方式实现AOP

1、切面类

package com.zisen.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 切面类
 */
@Component //却面对象的创建权限交给spring容器
@Aspect //aspectj框架的注解,标识当前类是一个切面类
public class MyAOP {

    public void before(){
        System.out.println("AOP前置通知:在目标方法执行之前被调用的通知。");
    }

    public void afterReturning(){
        System.out.println("AOP后置通知:在目标方法执行之后被调用的通知。");
    }


    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("AOP环绕通知:在目标方法执行之前调用的通知。");
        Object proceed = pjp.proceed();
        System.out.println("AOP环绕通知:在目标方法执行之后调用的通知。");
        return proceed;
    }

    public void exception(JoinPoint jp,Throwable ex){
        //一般会把异常发生的时间,位置,原因都记录下来
        System.out.println("AOP异常通知:在目标方法执行出现异常时被调用的通知。");
        System.out.println(jp.getSignature()+"方法出现异常,异常信息 :"+ex.getMessage());
    }

    public void myFinally(){
        System.out.println("AOP最终通知:无论是否出现异常,最终都会被调用的通知。");
    }

}

2、spring.xml注解实现AOP

<!--xml方式实现AOP-->
<aop:config>
    <!--声明切入点表达式,可以声明多个-->
    <aop:pointcut id="pt1" expression="execution(* com.zisen.service..*.*(..))"/>
    <aop:aspect ref="myAOP">
        <aop:before method="before" pointcut-ref="pt1"></aop:before>
        <aop:after-returning method="afterReturning" pointcut-ref="pt1"></aop:after-returning>
        <aop:after-throwing method="exception" pointcut-ref="pt1" throwing="ex"></aop:after-throwing>
        <aop:after method="myFinally" pointcut-ref="pt1"></aop:after>
        <aop:around method="around" pointcut-ref="pt1"></aop:around>
    </aop:aspect>
</aop:config>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值