Spring学习之AOP

    科技2022-08-25  97

    文章目录

    一、AOP概念二、静态/动态代理模式1、静态代理2、动态代理【重点】 三、AOP解析1、AOP术语2、advice 四、Spring实现AOP1、Spring API实现2、注解实现

    一、AOP概念

    1、什么是AOP

    面向切面编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。通俗描述:不通过修改源代码方式,在主干功能里面添加新功能

    2、Aop底层原理

    有接口,使用JDK动态代理无接口,使用CGLIB动态代理

    二、静态/动态代理模式

    1、静态代理

    优点:公共的业务由代理来完成 . 实现了业务的分工 缺点:类多了 , 多了代理类 , 工作量变大了 . 开发效率降低 静态代理角色分析

    抽象角色 : 一般使用接口或者抽象类来实现真实角色 : 被代理的角色代理角色 : 代理真实角色 ; 代理真实角色后 , 一般会做一些附属的操作 .客户 : 使用代理角色来进行一些操作 .

    代码实现 (1)抽象角色Rent . java

    //抽象角色:租房 public interface Rent { public void rent(); }

    (2)真实角色Host.java

    //真实角色: 房东,房东要出租房子 public class Host implements Rent{ public void rent() { System.out.println("房屋出租"); } }

    (3)代理角色

    //代理角色:中介 public class Proxy implements Rent { private Host host; public Proxy() { } public Proxy(Host host) { this.host = host; } //租房 public void rent(){ seeHouse(); host.rent(); fare(); } //看房 public void seeHouse(){ System.out.println("带房客看房"); } //收中介费 public void fare(){ System.out.println("收中介费"); } }

    (4)客户,一般去找代理

    //客户类,一般客户都会去找代理! public class Client { public static void main(String[] args) { //房东要租房 Host host = new Host(); //中介帮助房东 Proxy proxy = new Proxy(host); //你去找中介! proxy.rent(); } }

    2、动态代理【重点】

    动态代理的代理类是动态生成的 ,静态代理的代理类是我们提前写好的。

    一个动态代理可以代理多个类,代理的是接口

    动态代理分为两类 :一类是基于接口动态代理,一类是基于类的动态代理

    基于接口的动态代理-JDK动态代理基于类的动态代理–cglibjavasist

    JDK的动态代理需要了解两个类

    InvocationHandler【调用处理程序】Proxy【代理】

    使用JDK动态代理,使用Proxy类里面的方法创建代理对象 调用newProxyInstance方法 方法有三个参数: 第一参数,类加载器 第二参数,增强方法所在的类,这个类实现的接口,支持多个接口 第三参数,实现这个接口InvocationHandler,创建代理对象,写增强的部分

    (1)创建接口,定义方法

    public interface UserDao { public int add(int a,int b); public String update(String id); }

    (2)创建接口实现类,实现方法

    public class UserDaoImpl implements UserDao { @Override public int add(int a, int b) { return a+b; } @Override public String update(String id) { return id; } }

    (3)使用Proxy类创建接口代理对象

    public class JDKProxy { public static void main(String[] args) { //创建接口实现类代理对象 Class[] interfaces = {UserDao.class}; UserDaoImpl userDao = new UserDaoImpl(); UserDao dao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao)); int result = dao.add(1, 2); System.out.println("result:"+result);

    创建代理对象代码

    class UserDaoProxy implements InvocationHandler { //1 把创建的是谁的代理对象,把谁传递过来 //有参数构造传递 private Object obj; public UserDaoProxy(Object obj) { this.obj = obj; } //增强的逻辑 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //方法之前 System.out.println("方法之前执行...."+method.getName()+" :传递的参数..."+ Arrays.toString(args)); //被增强的方法执行 Object res = method.invoke(obj, args); //方法之后 System.out.println("方法之后执行...."+obj); return res; } }

    三、AOP解析

    AOP(Aspect Oriented Programming): 面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。 利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

    1、AOP术语

    横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 … 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。 目标(Target):被通知对象。 代理(Proxy):向目标对象应用通知之后创建的对象。 切入点(PointCut):切面通知 执行的 “地点”的定义。 连接点(JointPoint):与切入点匹配的执行点。 切入点表达式(execution):知道对哪个类里面的哪个方法进行增强


    切入点表达式语法结构:execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]) ) 举例: 对com.atguigu.dao.BookDao类里面的add进行增强 execution(* com.atguigu.dao.BookDao.add(…)) 对com.atguigu.dao.BookDao类里面的所有的方法进行增强 execution(* com.atguigu.dao.BookDao.* (…)) 对com.atguigu.dao包里面所有类,类里面所有方法进行增强 execution(* com.atguigu.dao.. (…))

    2、advice

    SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice 前置通知 后置通知 环绕通知 异常抛出通知 引介通知

    四、Spring实现AOP

    Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理

    1、Spring API实现

    (1)业务接口和实现类

    public interface UserService { public void add(); public void delete(); public void update(); public void search(); } public class UserServiceImpl implements UserService{ @Override public void add() { System.out.println("增加用户"); } @Override public void delete() { System.out.println("删除用户"); } @Override public void update() { System.out.println("更新用户"); } @Override public void search() { System.out.println("查询用户"); } }

    (2)前置增强类

    public class Log implements MethodBeforeAdvice { //method : 要执行的目标对象的方法 //objects : 被调用的方法的参数 //Object : 目标对象 @Override public void before(Method method, Object[] objects, Object o) throws Throwable { System.out.println( o.getClass().getName() + "的" + method.getName() + "方法被执行了"); } }

    (3)配置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" 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"> <!--注册bean--> <bean id="userService" class="com.lqr.service.UserServiceImpl"/> <bean id="log" class="com.lqr.log.Log"/> <bean id="afterLog" class="com.lqr.log.AfterLog"/> <!--aop的配置--> <aop:config> <!--切入点 expression:表达式匹配要执行的方法--> <aop:pointcut id="pointcut" expression="execution(* com.lqr.service.UserServiceImpl.*(..))"/> <!--执行环绕; advice-ref执行方法 . pointcut-ref切入点--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> </aop:config> </beans>

    2、注解实现

    1、创建类,在类里面定义方法

    public class User { public void add() { System.out.println("add......."); } }

    2、创建增强类(编写增强逻辑)

    (1)在增强类里面,创建方法,让不同方法代表不同通知类型

    public class UserProxy { public void before() { //前置通知 System.out.println("before......"); } }

    3、进行通知的配置 (1)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="com.atguigu.spring5.aopanno"></context:component-scan>

    (2)使用注解创建User和UserProxy对象

    @Component public class User{ } @Component public class UserProxy{ }

    (3)在增强类上面添加注解 @Aspect

    @Component @Aspect //生成代理对象 public class UserProxy { }

    (4)在spring配置文件中开启生成代理对象

    <!-- 开启Aspect生成代理对象--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    4、配置不同类型的通知 (1)在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

    //增强的类 @Component @Aspect //生成代理对象 public class UserProxy { //前置通知 //@Before注解表示作为前置通知 @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))") public void before() { System.out.println("before........."); } //后置通知(返回通知) @AfterReturning(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))") public void afterReturning() { System.out.println("afterReturning........."); } //最终通知 @After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))") public void after() { System.out.println("after........."); } //异常通知 @AfterThrowing(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))") public void afterThrowing() { System.out.println("afterThrowing........."); } //环绕通知 @Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))") public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("环绕之前........."); //被增强的方法执行 proceedingJoinPoint.proceed(); System.out.println("环绕之后........."); } }

    5、相同的切入点抽取

    //相同切入点抽取 @Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))") public void pointdemo() { } //前置通知 //@Before注解表示作为前置通知 @Before(value = "pointdemo()") public void before() { System.out.println("before........."); }

    6、有多个增强类多同一个方法进行增强,设置增强类优先级 在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

    @Component @Aspect @Order(1) public class PersonProxy{}

    7、完全使用注解开发 创建配置类,不需要创建xml配置文件

    @Configuration @ComponentScan(basePackages = {"com.atguigu"}) @EnableAspectJAutoProxy(proxyTargetClass = true) public class ConfigAop { }
    Processed: 0.009, SQL: 9