Spring学习笔记--面向切面编程(AOP)

时间:2023-03-09 07:38:20
Spring学习笔记--面向切面编程(AOP)

什么是AOP

AOP(Aspect Oriented Programming),意为面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

Spring学习笔记--面向切面编程(AOP)

AOP在Spring中的作用

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

  • 横切关注点:跨越应用程序多个模块的方法或功能,即与业务逻辑无关但需要关注的部分(日志、安全、缓存、事务等等)
  • 切面(Aspect):【横切关注点】模块化的特殊对象(一个类)
  • 通知(Advice):切面必须要完成的工作(类中方法)
  • 目标(Target):被通知目标
  • 代理(Proxy):向目标对象应用通知后创建的对象
  • 切入点(PointCut):切面通知执行的“地点”的定义
  • 连接点(JoinPoint):与切入点匹配的执行点

    Spring学习笔记--面向切面编程(AOP)

AOP实现

【搭建环境(普通Maven项目)】

导入依赖

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

【编写业务类(示例)】

  • UserService接口
package cn.iris.service;

/**
* @author Iris 2021/8/12
*/
public interface UserService { void add();
void del();
void update();
void query();
}
  • UserService实现类
package cn.iris.service;

/**
* @author Iris 2021/8/12
*/
public class UserServiceImpl implements UserService{ @Override
public void add() {
System.out.println("增加一个用户");
} @Override
public void del() {
System.out.println("删除一个用户");
} @Override
public void update() {
System.out.println("更新一个用户");
} @Override
public void query() {
System.out.println("查询一个用户");
}
}
  • 日志类(示例)
    • 前置日志类
package cn.iris.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

/**
* @author Iris 2021/8/12
*/
public class Log implements MethodBeforeAdvice { /**
* 前置日志
* @param method 要执行的目标对象的方法
* @param args 参数
* @param target 目标对象
* @throws Throwable
*/
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+ method.getName()+"被执行");
}
}
    • 结尾日志类
package cn.iris.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

/**
* @author Iris 2021/8/12
*/
public class AfterLog implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"的"+ method.getName()+"被执行后返回"+returnValue);
}
}
  • 测试类
import cn.iris.service.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* @author Iris 2021/8/12
*/
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationConfig.xml");
// 动态代理是代理的接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}

方式一:使用Spring的接口

【Spring API 接口实现】

  • 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 class="cn.iris.service.UserServiceImpl" id="userService"/>
<bean class="cn.iris.log.Log" id="log"/>
<bean class="cn.iris.log.AfterLog" id="afterLog"/> <!--方式一:使用原生Spring API接口-->
<!--配置aop(导入aop约束)-->
<aop:config>
<!--切入点 execution: 要执行的位置-->
<aop:pointcut id="point" expression="execution(* cn.iris.service.UserServiceImpl.*(..))"/> <!--执行环绕增加-->
<aop:advisor advice-ref="afterLog" pointcut-ref="point"/>
<aop:advisor advice-ref="log" pointcut-ref="point"/>
</aop:config> </beans>

方式二:使用自定义类实现

【重点:切面定义】

  • Class DiyPointCut
package cn.iris.diy;

/**
* @author Iris 2021/8/13
*/
public class DiyPointCut { public void before() {
System.out.println("-----Before Method-----");
} public void after() {
System.out.println("-----After Method-----");
}
}
  • applicationConfig.xml
<!--方式二:自定义类-->
<bean class="cn.iris.diy.DiyPointCut" id="diy"/>
<aop:config>
<!--自定义切面,ref引用自定义类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* cn.iris.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>

方式三:注解实现AOP

  • Class AnnotationPointCut
package cn.iris.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; /**
* 方式三:使用注解实现AOP
* @author Iris 2021/8/13
*/
@Aspect //标注该类为一个切面 public class AnnotationPointCut { @Before("execution(* cn.iris.service.UserServiceImpl.*(..))")
public void before() {
System.out.println("-----Before Method-----");
} @After("execution(* cn.iris.service.UserServiceImpl.*(..))")
public void after() {
System.out.println("-----After Method-----");
} @Around("execution(* cn.iris.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint pjp) {
System.out.println("-----Before Around Method-----");
try {
Signature signature = pjp.getSignature();
System.out.println("Signature : "+signature);
Object proceed = pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("-----After Around Method-----");
}
}
  • applicationConfig.xml
<!--方式三:使用注解实现AOP-->
<bean class="cn.iris.diy.AnnotationPointCut" id="anno"/>
<!--开启注解支持 JDK(默认:proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy/>