理解Spring AOP的实现方式与思想

Spring AOP简介

如果说IOC是Spring的核心,那么面向切面编程就是Spring最核心的功能之一了,在数据库事务中,面向切面编程被广泛应用。

AOP能够将那些与业务无关,却为业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来,便于减少系统的重复代码降低模块间的耦合度,并有利于未来的可拓展性和可维护性

面向切面编程

在OOP中,是面向对象开发,开发流程大致如下:

面向切面编程,关注的是切面,相当于在自上而下的流程中横插进去,这种方式的好处就是对代码的侵入性小,不会影响原有的实现业务。

Spring AOP名词介绍

在理解时,一定要先搞清楚AOP部分名词的含义,这样可以让你更好理解。

官方英文文档:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#aop

其中:

  • Aspect

切面,一种开发思想,很好地例子就是事务管理。

  • Join Point

程序执行过程中的一点,例如方法的执行或异常的处理。

  • Advice

通知,可以表示在执行点前、后或者前后执行的一种状态。

  • Pointcut

切入点,表示在执行到某一个状态或标志时(具体可表示某一方法、注解或类等),执行切面增强的方法。

  • Introduction

代表类型声明其他方法或字段。

  • Target object

目标对象,即为原始切入的对象。

  • AOP proxy

增强对象方法后的代理对象,在AOP中,使用的是JDK或CGLIB动态代理,此proxy即为动态代理生成的对象。

  • Weaving

织入,运行时为增强方法后的对象生成代理对象。

使用注解开发Sping AOP

需求说明:用AOP实现日志记录功能,需要记录方法实现时间。

分析图:

Maven项目引入所需包:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.2</version>
</dependency>

项目目录:

首先写一个业务方法:

package com.yl.service;

import org.springframework.stereotype.Service;

@Service
public class DemoService {

	public void doMethod() {
		System.out.println("调用Service方法");
	}
}

定义切面:

  • execution表达式

基本语法

execution(<修饰符模式>?<返回类型模式><方法名模式>(<参数模式>)<异常模式>?)  除了返回类型模式、方法名模式和参数模式外,其它项都是可选的。

execution(* com.yl.service...(..))

符号 含义
execution() 表达式主体
第一个“*”符号 表示任何类型的返回值
com.yl.service 表示业务类的包路径
“..”符号 表示当前包及子包
第二个“*“符号 表示所有类
“.*(..)” 表示任何方法名,(..)表示任意参数
package com.yl.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

// 将类声明成IOC中的bean
@Component
// 声明这是一个切面
@Aspect
public class DemoAspect {

	/**
	 * 定义切入点
	 */
	@Pointcut("execution(* com.yl.service..*.*(..))")
	public void servicePointcut() {

	}

	/**
	 * 后置通知
	 */
	@After("servicePointcut()")
	public void doAfter() {
		System.out.println("执行后置方法");
	}

	/**
	 * 前置通知
	 */
	@Before("servicePointcut()")
	public void doBefore() {
		System.out.println("执行前置方法");
	}

	/**
	 * 环绕通知
	 * @throws Throwable 
	 */
	@Around("servicePointcut()")
	public void doAdvice(ProceedingJoinPoint joinPoint){
		long start = System.currentTimeMillis();
		try {
			// 执行被切入方法
			joinPoint.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		long stop = System.currentTimeMillis();
		long time = stop - start;
		System.out.println("执行时长:" + time);
	}
}

配置开启AOP自动代理,包扫描路径:

package com.yl.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("com.yl") // 包扫描路径,表示需要扫描到IOC中的bean的路径
@EnableAspectJAutoProxy // 默认使用JDK代理,将proxyTargetClass传为true则为使用CGLIB代理
public class ProjectConfig {

}

启动类:

package com.yl;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.yl.config.ProjectConfig;
import com.yl.service.DemoService;

public class Test {
	public static void main(String[] args) {
                @SuppressWarnings("resource")
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ProjectConfig.class);
		DemoService demoService = context.getBean(DemoService.class);
		demoService.doMethod();
	}
}

运行结果:

执行前置方法
调用Service方法
执行时长:15
执行后置方法

此程序利用AOP面向切面编程的思想,实现了基本的日志记录功能,更多功能可以通过Spring官网或其他途径继续了解。

如果您对AOP的JDK、CGLIB动态代理感兴趣,请移步《关于Java代理那些事儿》

原文地址:https://www.cnblogs.com/yl-space/p/13638574.html