【Spring】(十一)AOP实现方式

AOP实现方式

https://blog.csdn.net/qq_33369905/article/details/105828920


1.什么是AOP

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

2.AOP在Spring中的作用

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

  • 名词解释:

    • 横切关注点:跨越应用程序多个模块的方法或功能,与业务逻辑无关。如日志,安全,缓存,事务等。
    • 切面(Aspect):横切关注点 被模块化 的特殊对象。是一个类。
    • 通知(Advice):切面必须要完成的工作。是类中的一个方法。
    • 目标(Target):被通知对象。
    • 代理(Proxy):向目标对象应用通知之后创建的对象。
    • 切入点(PointCut):切面通知 执行的“地点”的定义。
    • 连接点(JointPoint):与切入点匹配的执行点。
  • Spring AOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice。AOP在不改变原有代码的情况下,增加新功能。

    • 前置通知 MethodBeforeAdvice
    • 后置通知 AfterReturningAdvice
    • 环绕通知 MethodInterceptor
    • 异常抛出通知 ThrowsAdvice
    • 引介通知 IntroductionInterceptor

3.使用Spring实现aop

3.1 方式一:使用Spring的API接口【主要SpringAPI接口实现】

  • 1.导入maven依赖

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.6</version>
    </dependency>
    
  • 2.UserService

    public interface UserService {
        public void add();
    
        public void delete();
    
        public void update();
    
        public void select();
    }
    
  • 3.UserServiceImpl

    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 select() {
            System.out.println("查询了一个用户");
        }
    
    }
    
  • 4.Log

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

    public class AfterLog implements AfterReturningAdvice {
    
        //returnValue:返回值
        public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
            System.out.println("执行了" + method.getName() + "方法,返回结果为:" + returnValue);
    
        }
    }
    
  • 6.applicationContext.xml

    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!--注册bean-->
        <bean id="userService" class="service.UserServiceImpl"/>
        <bean id="log" class="log.Log"/>
        <bean id="afterLog" class="log.AfterLog"/>
    
        <!--方式一:使用原生Spring API接口-->
        <!--配置aop:需要导入aop的约束-->
        <aop:config>
            <!--切入点:expression:表达式,execution(要执行的方法 * * * * * )-->
            <aop:pointcut id="pointcut" expression="execution(* service.UserServiceImpl.*(..))" />
    
            <!--执行环绕;advice-ref 执行方法,pointcut-ref 切入点 -->
            <!--log和afterLog切入点在pointcut-->
            <aop:advisor advice-ref="log" pointcut-ref="pointcut" />
            <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut" />
        </aop:config>
    
    </beans>
    
  • 7.测试类

    public class MyTest {
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    
            //报错
    //        UserServiceImpl userService = context.getBean("userService", UserServiceImpl.class);
    
            //动态代理代理的是接口
            UserService userService = context.getBean("userService", UserService.class);
    
            userService.add();
        }
    }
    

  • p.s:Spring的execution表达式

    https://blog.csdn.net/weixin_39986856/article/details/82657750


3.2 方式二:自定义实现AOP【主要是切面定义】

  • 新增切面类 DiyPointCut

    public class DiyPointCut {
        public void before() {
            System.out.println("======方法执行前======");
        }
    
        public void after() {
            System.out.println("======方法执行后======");
        }
    }
    
  • applicationContext.xml中

    <!--方法二:自定义切面实现-->
    <!--注册bean-->
    <bean id="userService" class="service.UserServiceImpl"/>
    <bean id="diy" class="diy.DiyPointCut" />
    
    <aop:config>
            <!--自定义切面,ref 要引用的类-->
            <aop:aspect ref="diy">
                <!--切入点-->
                <aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))" />
                <!--通知-->
                <aop:before method="before" pointcut-ref="point"/>
                <aop:after method="after" pointcut-ref="point"/>
            </aop:aspect>
    </aop:config>
    


3.3 方式三:使用注解实现

  • AnnotationPointCut

    //方式三:使用注解实现
    @Aspect
    public class AnnotationPointCut {
    
        @Before("execution(* service.UserServiceImpl.*(..))")
        public void before(){
            System.out.println("======方法执行前======");
        }
    
        @After("execution(* service.UserServiceImpl.*(..))")
        public void after(){
            System.out.println("======方法执行后======");
        }
    
        //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
        @Around("execution(* service.UserServiceImpl.*(..))")
        public void around(ProceedingJoinPoint jp) throws Throwable{
            System.out.println("环绕前");
            Object proceed = jp.proceed();  //执行方法
            System.out.println("环绕后");
        }
    }
    
  • 配置文件中:或可以在类上使用注解@Component

    <!--方式三-->
    <bean id="userService" class="service.UserServiceImpl"/>
    <bean id="annotationPointCut" class="diy.AnnotationPointCut" />
    <!--开启注解支持  JDK(默认 proxy-target-class="false")  cglib(proxy-target-class="true")-->
    <aop:aspectj-autoproxy />
    

  • AnnotationPointCut的around方法中,打印获取signature

     public void around(ProceedingJoinPoint jp) throws Throwable {
            Signature signature = jp.getSignature(); //获得签名
            。。。
    }
    

    结果

    signature:void service.UserService.delete()
    
posted @ 2021-01-26 22:11  musecho  阅读(153)  评论(0)    收藏  举报