基本概念
AOP,面向切面编程,利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
通俗描述:不通过修改源代码方式,在主干功能里面添加新功能
底层原理
动态代理技术,有两种情况
-
有接口情况,使用JDK动态代理
创建接口实现类代理对象,增强类的方法
-
没有接口情况,使用CGLIB动态代理
创建子类代理对象,增强类的方法
动态代理可以参考我的另一篇文章:设计模式之动态代理
AOP术语
连接点
类里面哪些方法可以被增强,这些方法称为连接点
切入点
切入点:实际被真正增强的方法称为切入点
通知(增强)
通知(增强):实际增强的逻辑部分称为通知,且分为以下五种类型:
- 前置通知
- 后置(返回)通知
- 环绕通知 前后通知
- 异常通知 类比catch
- 最终通知 类比finally
切面
把通知应用到切入点过程
AOP用法
AspectJ
AspectJ是一个独立的aop框架,它不是aop的组成部分。一般把AsepctJ和Spring框架一起使用,进行aop操作。
spring如何使用aspectJ
AspectJ 本身是不支持运行期织入的,日常使用时候,我们经常回听说,spring 使用aspectJ实现了aop,听起来好像spring的aop完全是依赖于aspectJ
其实spring对于aop的实现是通过动态代理(jdk的动态代理或者cglib的动态代理),它只是使用了aspectJ的Annotation,并没有使用它的编译期和织入器,也就是说spring并不是直接使用aspectJ实现aop的
spring aop与aspectJ的区别
- spring aop 使用AspectJ语法的一个子集,一些method call, class member set/get 等aspectJ支持的语法它都不支持
- spring aop 底层是动态代理,所以受限于这点,有些增强就做不到,比如调用自己的方法就无法走代理
参考:https://www.jianshu.com/p/958af6a90477
切入点表达式
切入点表达式作用:知道对哪个类里面的哪个方法进行增强
语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称] ([参数列表]) )
-
eg1: 对com.eh.eden.dao.BookDao类里面的add进行增强
execution(* com.atguigu.dao.BookDao.add(..))
-
eg2: 对com.eh.eden.dao.BookDao类里面的所有方法进行增强
execution(* com.atguigu.dao.BookDao.*(..))
-
eg3: 对com.eh.eden.dao包下面的所有类的所有方法进行增强
execution(* com.atguigu.dao.*.*(..))
前置工作
aop依赖AspectJ,所以需要引入AspectJ相关jar包
1
2
3
4
5
6
7
8
|
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
|
增加aop namespace
1
2
3
4
5
6
7
8
9
|
<?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:p="http://www.springframework.org/schema/p"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
|
基于注解方式实现AOP操作
演示
被增强类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package com.eh.eden.spring.demo.aop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* 被增强类
*/
@Component
public class UserDao {
private final Logger logger = LoggerFactory.getLogger(UserDao.class);
public void login() {
logger.info("==========> user login");
}
}
|
增强类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
package com.eh.eden.spring.demo.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
/**
* 被增强类
*/
@Component
@Aspect
public class UserProxy {
private final Logger logger = LoggerFactory.getLogger(UserDao.class);
// 前置通知
@Before(value = "execution(* com.eh.eden.spring.demo.aop.UserDao.login(..))")
public void before() {
logger.info("========> 前置通知");
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserDao userDao = context.getBean("userDao", UserDao.class);
userDao.login();
}
}
|
开启注解扫描和开启生成代理对象
1
2
3
|
<context:component-scan base-package="com.eh.eden.spring.demo.aop"/>
<!--开启 Aspect注解生成代理对象-->
<aop:aspectj-autoproxy/>
|
测试
UserProxy.main
1
2
|
20201012 23:38:45 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 前置通知
20201012 23:38:45 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ==========> user login
|
5种类型通知执行顺序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
package com.eh.eden.spring.demo.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
/**
* 被增强类
*/
@Component
@Aspect
public class UserProxy {
private final Logger logger = LoggerFactory.getLogger(UserDao.class);
@Pointcut("execution(* com.eh.eden.spring.demo.aop.UserDao.login(..))")
public void point_UserDao_login() {
}
// 前置通知
@Before(value = "point_UserDao_login()")
public void before() {
logger.info("========> 前置通知 Before");
}
// 后置通知
@AfterReturning(value = "point_UserDao_login()")
public void afterReturning() {
logger.info("========> 后置通知 AfterReturning");
}
// 环绕通知
@Around(value = "point_UserDao_login()")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
logger.info("========> 环绕通知 之前 Around");
proceedingJoinPoint.proceed();
logger.info("========> 环绕通知 之后 Around");
}
// 异常通知
@AfterThrowing(value = "point_UserDao_login()")
public void afterThrowing() {
logger.info("========> 异常通知 AfterThrowing");
}
// 最终通知
@After(value = "point_UserDao_login()")
public void after() {
logger.info("========> 最终通知 After");
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserDao userDao = context.getBean("userDao", UserDao.class);
userDao.login();
}
}
|
正常执行顺序
1
2
3
4
5
6
|
20201012 23:46:36 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 环绕通知 之前 Around
20201012 23:46:36 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 前置通知 Before
20201012 23:46:36 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ==========> user login
20201012 23:46:36 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 后置通知 AfterReturning
20201012 23:46:36 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 最终通知 After
20201012 23:46:36 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 环绕通知 之后 Around
|
异常执行顺序
1
2
3
4
5
6
7
8
9
|
@Component
public class UserDao {
private final Logger logger = LoggerFactory.getLogger(UserDao.class);
public void login() {
logger.info("==========> user login");
int i = 1 / 0;
}
}
|
结果:
1
2
3
4
5
6
|
20201012 23:48:35 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 环绕通知 之前 Around
20201012 23:48:35 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 前置通知 Before
20201012 23:48:35 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ==========> user login
20201012 23:48:35 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 异常通知 AfterThrowing
20201012 23:48:35 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ========> 最终通知 After
Exception in thread "main" java.lang.ArithmeticException: / by zero
|
小结
- 环绕通知在最外层
- 程序异常时后置通知不会执行
- 最终通知时钟都会执行
抽取相同的切入点
1
2
3
4
5
6
7
8
9
|
@Pointcut("execution(* com.eh.eden.spring.demo.aop.UserDao.login(..))")
public void point_UserDao_login() {
}
// 前置通知
@Before(value = "point_UserDao_login()")
public void before() {
logger.info("========> 前置通知");
}
|
设置增强类优先级
有多个增强类对同一个被增强类的方法进行增强时,需要设置增强类的优先级。
在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高。
1
2
3
4
5
6
7
8
9
10
|
@Component
@Aspect
@Order(1)
public class UserProxy {
@Component
@Aspect
@Order(2)
public class UserProxy2 {
|
执行结果,可以看到两者按照顺序执行
1
2
3
4
5
6
7
8
9
10
11
|
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy - ========> 环绕通知 之前 Around
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy - ========> 前置通知 Before
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy2 - ========> 环绕通知 之前 Around
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy2 - ========> 前置通知 Before
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ==========> user login
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy2 - ========> 后置通知 AfterReturning
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy2 - ========> 最终通知 After
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy2 - ========> 环绕通知 之后 Around
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy - ========> 后置通知 AfterReturning
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy - ========> 最终通知 After
20201012 23:52:19 [main] INFO com.eh.eden.spring.demo.aop.UserProxy - ========> 环绕通知 之后 Around
|
纯注解开发aop
创建配置类,不需要创建xml配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package com.eh.eden.spring.demo;
import com.eh.eden.spring.demo.aop.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan(basePackages = {"com.eh.eden.spring.demo.aop"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SpringConfig {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserDao userDao = context.getBean("userDao", UserDao.class);
userDao.login();
}
}
|
基于配置文件方式实现AOP操作
了解即可,示例如下
beans_aop.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<?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:p="http://www.springframework.org/schema/p"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--创建增强类和被增强类对象-->
<bean id="userDao" class="com.eh.eden.spring.demo.aop.UserDao"/>
<bean id="userProxy" class="com.eh.eden.spring.demo.aop.UserProxy"/>
<!--配置aop增强-->
<aop:config>
<!--切入点-->
<aop:pointcut id="p" expression="execution(* com.eh.eden.spring.demo.aop.UserDao.login(..))"/>
<!--配置切面-->
<aop:aspect ref="userProxy">
<!--增强方法->切入点-->
<aop:before method="before" pointcut-ref="p"/>
</aop:aspect>
</aop:config>
</beans>
|
测试
1
2
3
4
5
6
7
|
public static void main(String[] args) {
// 1. 加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans_aop.xml");
// 2. 获取配置创建的对象
UserDao userDao = context.getBean("userDao", UserDao.class);
userDao.login();
}
|
运行结果:
1
2
|
20201013 00:05:40 [main] INFO com.eh.eden.spring.demo.aop.UserProxy - ========> 前置通知 Before
20201013 00:05:40 [main] INFO com.eh.eden.spring.demo.aop.UserDao - ==========> user login
|