Spring AOP

Spring AOP

一、AOP简介

AOP是OOP的延续,是Aspect Oriented Programming的缩写,意思是面向切面编程。可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。AOP实际是GoF设计模式的延续,设计模式孜孜不倦追求的是调用者和被调用者之间的解耦,AOP可以说也是这种目标的一种实现。

我们现在做的一些非业务,如:日志、事务、安全等都会写在业务代码中(也即是说,这些非业务类横切于业务类),但这些代码往往是重复,复制——粘贴式的代码会给程序的维护带来不便,AOP就实现了把这些业务需求与系统需求分开来做。这种解决的方式也称代理机制(代理模式在笔者上篇博文中)。
在这里插入图片描述
在这里插入图片描述

二、AOP在Spring中的作用

提供声明式事务; 允许用户自定义切面

横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …

切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。

通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。

目标(Target):被通知对象。

代理(Proxy):向目标对象应用通知之后创建的对象。

切入点(PointCut):切面通知 执行的 “地点”的定义。

连接点(JointPoint):与切入点匹配的执行点。
在这里插入图片描述
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
在这里插入图片描述
即 aop 在 不改变原有代码的情况下 , 去增加新的功能 .

三、使用SpringAPI实现AOP

  1. 编写业务类

    接口

    package org.westos.service;
    
    public interface UserService {
        void add();
        void delete();
        void update();
        void query();
    }
    

    实现类

    package org.westos.service;
    
    public class UserServiceImpl implements UserService {
    
        public void add() {
            System.out.println("增加了一个用户");
        }
    
        public void delete() {
            System.out.println("删除了一个用户");
        }
    
        public void update() {
            System.out.println("更新了一个用户");
        }
    
        public void query() {
            System.out.println("查询了一个用户");
        }
    }
    
  2. 定义日志增加类实现

    package org.westos.log;
    
    import org.springframework.aop.MethodBeforeAdvice;
    
    import java.lang.reflect.Method;
    
    public class BeforeLog implements MethodBeforeAdvice {
        //method:要执行的目标对象的方法
        //objects:要被调用的方法的参数
        //o:目标对象
        public void before(Method method, Object[] objects, Object o) throws Throwable {
            System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
        }
    }
    
    package org.westos.log;
    
    import org.springframework.aop.AfterReturningAdvice;
    
    import java.lang.reflect.Method;
    
    public class AfterLog implements AfterReturningAdvice {
        public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
            System.out.println("执行了"+o1.getClass().getName()+"的"+method.getName()+"方法,返回值是"+o);
        }
    }
    
  3. 编写Spring核心配置文件

    注意需要导入约束,使用aop切入时直接切入切入点,然后执行通知

    <?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">
        
        <!--注册service的bean-->
        <bean id="UserService" class="org.westos.service.UserServiceImpl"/>
    
        <!--注册日志类的bean-->
        <bean id="beforeLog" class="org.westos.log.BeforeLog"/>
        <bean id="afterLog" class="org.westos.log.AfterLog"/>
    
        <!--使用Spring的aop切入-->
        <aop:config>
            <!--切入点
            expression 表达式,表示要切入的位置
            语法:execution([类的修饰符] [类的全路径] [方法] [参数])
            -->
            <aop:pointcut id="pointCut" expression="execution(* org.westos.service.UserServiceImpl.*(..))"/>
            <!--执行通知,增强-->
            <aop:advisor advice-ref="beforeLog" pointcut-ref="pointCut"/>
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointCut"/>
        </aop:config>
    
    </beans>
    
  4. 测试类

    需要先导入aop的织入包

    https://mvnrepository.com/artifact/org.aspectj/aspectjweaver/1.8.9

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.9</version>
    </dependency>
    

    编写测试类

    package org.westos.service;
    
    import org.junit.Test;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class SpringAopTest {
        @Test
        public void test(){
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            UserService userService = (UserService) context.getBean("UserService");
            userService.add();
        }
    }
    

    测试结果:
    在这里插入图片描述

  5. 注意spring调用的是真实对象userService,暗箱中: 动态的修改userService,在方法的前后或者其他通知的地方增加了我们的切入代码。我们就可以实现依旧调用原来的对象,产生增加新的业务的功能

四、自定义类实现AOP

  1. 业务类和之前一样

  2. 自定义AOP增强类,即切面

    package org.westos.diy;
    
    public class Diy {
        public void before(){
            System.out.println("业务方法执行前");
        }
    
        public void after(){
            System.out.println("业务方法执行后");
        }
    }
    
  3. 注入bean并使用aop进行增强

    注意:使用自定义类实现aop时需先切入切入面,再切入切入点

    <?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">
    
        <!--注册service的bean-->
        <bean id="userService" class="org.westos.service.UserServiceImpl"/>
    
        <!--注册自定义的Aop增强类-->
        <bean id="diy" class="org.westos.diy.Diy"/>
    
        <!--使用Aop增强-->
        <aop:config>
            <!--注意使用自定义类型实现aop时在要在切面下进行切入点配置-->
            <!--切面-->
            <aop:aspect ref="diy">
                <aop:pointcut id="diyPointCut" expression="execution(* org.westos.service.UserServiceImpl.*(..))"/>
                <aop:before method="before" pointcut-ref="diyPointCut"/>
                <aop:after method="after" pointcut-ref="diyPointCut"/>
            </aop:aspect>
        </aop:config>
    
    </beans>
    
  4. 测试类

    package org.westos.service;
    
    import org.junit.Test;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class SpringAopTest2 {
        @Test
        public void test(){
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            UserService userService = (UserService) context.getBean("userService");
            userService.add();
        }
    }
    
  5. 测试结果
    在这里插入图片描述

五、使用注解实现AOP

使用注解@before @after…等简化切入

  1. 业务类和之前一样

  2. 编写增强的类,写注解

    • 需要将类注解为切面
    • 方法上就是,切入点,增强
    package org.westos.annotation;
    
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    
    
    @Aspect
    public class annotation {
        @Before("execution(* org.westos.service.UserServiceImpl.*(..))")
        public void before(){
            System.out.println("业务方法执行前");
        }
    
        @After("execution(* org.westos.service.UserServiceImpl.*(..))")
        public void after(){
            System.out.println("业务方法执行后");
        }
    }
    
  3. 配置文件

    注意使用注解实现Aop时必须设置自动代理,否则业务方法及其之后的方法不能被执行

    <?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">
    
        <!--注入service实体类-->
        <bean id="userService" class="org.westos.service.UserServiceImpl"/>
    
        <!--注解实现aop类-->
        <bean id="annotation" class="org.westos.annotation.annotation"/>
    
        <!--识别注解,自动代理-->
        <!--注意使用注解实现Aop时必须设置自动代理,否则业务方法及其之后的方法不能被执行-->
        <aop:aspectj-autoproxy/>
    </beans>
    
  4. 测试类

    package org.westos.service;
    
    import org.junit.Test;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class SpringAopTest3 {
        @Test
        public void test(){
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");
            UserService userService = (UserService) context.getBean("userService");
            userService.add();
        }
    }
    
  5. 测试结果

    在这里插入图片描述

六、AOP小结

  • 本质就是动态代理

  • 需要到一个包,用来进行aop织入的包: aspectjweaver

  • 注意别遗漏了切面;

  • 三种实现AOP的方法

    • 使用SpringAPI来实现AOP
    • 使用自定义类来实现AOP
    • 使用注解实现AOP
  • 使用SpringAPI实现AOP直接切入切入点

    使用自定义类实现AOP先切入切入面

    使用注解实现AOP必须设置自动代理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值