Spring AOP面向切面编程实现原理方法详解

 更新时间:2020年08月05日 09:27:04   作者:弥漫s  
这篇文章主要介绍了Spring AOP面向切面编程实现原理方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1. 什么是AOP

AOP (Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现在不修改源代码的情况下,给程序动态统一添加功能的一种技术,可以理解成动态代理。是Spring框架中的一个重要内容。利用 AOP 可以对业务逻辑的各个部分进行隔离,使业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高开发的效率

2. Spring AOP

①. AOP 在Spring中的作用

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

②. AOP 的基本概念

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

  • Aspect(切面):横切关注点被模块化的特殊对象。通常是一个类,里面可以定义切入点和通知
  • Weaving(织入):把切面(aspect)连接到其它的应用程序类型或者对象上,并创建一个被通知(advised)的对象。 这些可以在编译时,类加载时和运行时完成。Spring和其它纯Java AOP框架一样,在运行时完成织入
  • Advice(通知):AOP在特定的切入点上执行的增强处理,是切面必须要完成的工作,也是类中的一个方法
  • Target(目标):被通知对象
  • AOP(代理):AOP框架创建的对象,代理就是目标对象的加强。Spring中的 AOP 代理可以是 JDK 动态代理,也可以是 CGLIB 代理,前者基于接口,后者基于子类
  • JointPoint(连接点):程序执行过程中明确的点,一般是方法的调用
  • Pointcut(切入点):就是带有通知的连接点,与切入点匹配的执行点

③. 使用Spring实现Aop

前提

使用AOP织入,需要导入一个依赖包

<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.5</version>
</dependency>

实现Aop的三种方式

方式一:通过 Spring API 实现【主要是springAPI接口实现】

首先编写业务接口和实现类

public interface UserService {
  public void add();
  public void delete();
  public void update();
  public void search();
}

 

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("查询了一个用户");
  }
}

接着编写增强类,这里写两个:前置增强Log和后置增强AfterLog

import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
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()+"被执行了");
  }
}
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
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);
  }
}

最后在Spring的文件中注册( applicationContext.xml ),并实现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
    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="com.lf.service.UserServiceImpl"/>
  <bean id="log" class="com.lf.log.Log"/>
  <bean id="afterLog" class="com.lf.log.AfterLog"/>
  
  <!--方式一:使用原生Spring API接口 -->
  <!--配置aop:需要导入aop的约束-->
  <aop:config>
  <!--切入点:expression:表达式,execution(要执行的位置! * * * * *) -->
  <aop:pointcut id="pointcut" expression="execution(* com.lf.service.UserServiceImpl.*(..))"/>
  <!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
  <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
  <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
  </aop:config>

</beans>

进行测试:

import com.lf.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
  @Test
  public void test(){
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService1 = (UserService) context.getBean("userService");
  UserService userService = (UserService) context.getBean("userService");
  userService.add();
  }
}

运行结果:

com.lf.service.UserServiceImpl的add被执行了
增加了一个用户
执行了add方法,返回结果为:null

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

目标业务类不变,还是方式一中的UserServiceImpl

写入一个切入类

public class DiyPointCut {
  public void before(){
    System.out.println("========方法执行前=========");
  }

  public void after(){
    System.out.println("========方法执行后=========");
  }
}

在Spring中配置(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="com.lf.service.UserServiceImpl"/>
  <bean id="log" class="com.lf.log.Log"/>
  <bean id="afterLog" class="com.lf.log.AfterLog"/>
  
  <!--方式二:自定义类-->
  <bean id="diy" class="com.lf.diy.DiyPointCut"/>

  <aop:config>
  <!--自定义切面, ref 要引用的类-->
  <aop:aspect ref="diy">
  <!--切入点-->
  <aop:pointcut id="point" expression="execution(* com.lf.service.UserServiceImpl.*(..))"/>
  <!--通知-->
  <aop:before method="before" pointcut-ref="point"/>
  <aop:after method="after" pointcut-ref="point"/>
  </aop:aspect>
  </aop:config>
</beans>

在上面的 MyTest.java 中测试,得到结果:

========方法执行前=========
增加了一个用户
========方法执行后=========

方式三:使用注解实现【多用】

编写一个注解实现的增强类

package com.lf.diy;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

  @Before("execution(* com.lf.service.UserServiceImpl.*(..))")
  public void before(){
    System.out.println("=====方法执行前======");
  }

  @After("execution(* com.lf.service.UserServiceImpl.*(..))")
  public void after(){
    System.out.println("=====方法执行后======");
  }

  //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点;
  @Around("execution(* com.lf.service.UserServiceImpl.*(..))")
  public void around(ProceedingJoinPoint jp) throws Throwable {
    System.out.println("环绕前");
    Signature signature = jp.getSignature();//获得签名
    System.out.println("signature:"+signature);

    Object proceed = jp.proceed();  //执行方法
    System.out.println("环绕后");

    System.out.println(proceed);
  }

}

在Spring配置文件中,注册bean,并增加支持注解的配置

<?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="com.lf.service.UserServiceImpl"/>
  <bean id="log" class="com.lf.log.Log"/>
  <bean id="afterLog" class="com.lf.log.AfterLog"/>

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

在 MyTest.java 中测试

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

得到结果:

环绕前
signature:void com.lf.service.UserService.add()
=====方法执行前======
增加了一个用户
=====方法执行后======
环绕后
null

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Spring配置类源码分析详解

    Spring配置类源码分析详解

    这篇文章主要介绍了Spring配置类解析源码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-09-09
  • Java图形用户界面之列表框

    Java图形用户界面之列表框

    列表框通过Swing组件JList产生,其总是在屏幕上占据固定行数的空间。这篇文章主要介绍了java图形用户界面之列表框的相关资料,非常不错具有参考借鉴价值,需要的朋友可以参考下
    2016-10-10
  • 全面解析Spring Security 过滤器链的机制和特性

    全面解析Spring Security 过滤器链的机制和特性

    这篇文章主要介绍了Spring Security 过滤器链的机制和特性,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • Spring中的10种事务失效的常见场景

    Spring中的10种事务失效的常见场景

    这篇文章主要介绍了Spring中的10种事务失效的常见场景,Spring的声明式事务功能更是提供了极其方便的事务配置方式,配合Spring Boot的自动配置,大多数Spring Boot项目只需要在方法上标记@Transactional注解,即可一键开启方法的事务性配置,需要的朋友可以参考下
    2023-11-11
  • java实现/创建线程的几种方式小结

    java实现/创建线程的几种方式小结

    在JAVA中,用Thread类代表线程,所有线程对象都必须是Thread类或者Thread类子类的实例,下面这篇文章主要介绍了java实现/创建线程的几种方式,需要的朋友可以参考下
    2021-08-08
  • IDEA Debug过程中使用Drop Frame或Reset Frame实现操作回退的方法

    IDEA Debug过程中使用Drop Frame或Reset Frame实现操作回退的方法

    在IDEA中就提供了一个帮助你回退代码的机会,但这个方法并不是万能的,好了,下面就来具体说说IDEA Debug过程中使用Drop Frame或Reset Frame实现操作回退的方法,感兴趣的朋友一起看看吧
    2022-04-04
  • SpringCloud开启session共享并存储到Redis的实现

    SpringCloud开启session共享并存储到Redis的实现

    这篇文章主要介绍了SpringCloud开启session共享并存储到Redis的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • java实现简单图片上传下载功能

    java实现简单图片上传下载功能

    这篇文章主要为大家详细介绍了java实现简单图片上传下载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-10-10
  • 面试题:Java 实现查找旋转数组的最小数字

    面试题:Java 实现查找旋转数组的最小数字

    这篇文章主要介绍了Java 实现查找旋转数组的最小数字,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • 完美解决Spring Boot前端的Access-Control-Allow-Origin跨域问题

    完美解决Spring Boot前端的Access-Control-Allow-Origin跨域问题

    这篇文章主要介绍了完美解决Spring Boot前端的Access-Control-Allow-Origin跨域问题,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05

最新评论