[Spring]AOP概念扫盲与操作指南
本文是于2020-4-25重构,将文章中关于Spring的理念介绍移至:
本文为IOC的实操部分,介绍Spring的一些基本操作
你最后已经掌握spring的一些基本操作,在
[Spring]关于IOC控制反转,你应该掌握这些中,我详细介绍了如何上手spring及其IOc操作
学AOP前你必须懂的专业名词
AOP基于动态代理模式
- CGlib动态代理基于类
- JDK动态代理基于接口
如果以下概念看不懂没关系,看下面实操代码就整明白了
Jionpoint连接点):要拦截的目标方法
Pointcut(切点):拦截目标方法后所执行的方法
Advice(通知):在连接点前后或异常情况来做的事情,分为前置通知,后置通知,返回通知,异常通知,环绕通知
Aspect(切面):切点和通知组成
Target(目标对象):代理的目标对象,如上图
Weave(织入):切面应用到目标对象并且导致proxy(代理)对象创建的过程叫织入
AOP环境配置
你需要从Maven仓库找到以下红色框内的包,版本不要求,导入你的项目中【通过坐标】
Spring配置文件内容(AplicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<!-- 开启以注解形式切面的驱动 -->
<aop:aspectj-autoproxy/>
</beans>
定义切面
- 创建一个类,在上加入@Aspect注解
- 在任意方法上加上切点注解@PointCut并配好execution属性(确定拦截目标)
- 定义前置通知并关联切点注解的方法
package com.aspect;
import com.model.User;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
//切面类加上注解@Aspect
@Aspect
public class PermAspect {
/*
* 第一个*:拦截方法的返回值,*代表任意
* 第一个..子包下
* 第二个*:所有的类
* 第三个*:所有的方法
* 第二个..所有的参数
* */
@Pointcut("execution(* com.service..*.*(..))")
public void anyMethod(){
}
/*
*Before前置通知
*anyMethod():指定前置通知的切点
*args(参数)
* */
@Before("anyMethod()&&args(user)")
/*或者写成以下形式
* @Before(value = "anyMethod()&&args(param)",argNames = "param")
* */
public void preAdvice(User user){
System.out.println(user);
System.out.println("执行前置通知");
}
}
在配置文件中配置切面bean与被切的目标bean
<!--定义被切的bean-->