视频链接:Spring5框架最新版教程
文章源码:https://github.com/geyiwei-suzhou/spring5/
AOP基本概念
什么是AOP? 通俗描述:不通过修改源代码方式,在主干功能里面添加新功能
AOP底层原理
AOP底层使用动态代理,有两种情况的动态代理
- 有接口情况,使用JDK动态代理
创建接口实现类代理对象,增强类的方法 - 没有接口情况,使用CGLIB动态代理
创建子类的代理对象,增强类的方法
AOP(JDK动态代理)
使用JDK动态代理,使用java.lang.reflect.Proxy类里面的newProxyInstance方法创建
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) { .... }
方法三个参数:
- 类加载器
- 增强方法所在的类,这个类实现的接口,支持多个接口
- 实现这个接口InvocationHandler,创建代理对象,写增强的部分
编写JDK动态代理代码
UserDao
package com.antherd.spring5;
public interface UserDao {
int add(int a, int b);
String update(String id);
}
UserDaoImpl
package com.antherd.spring5;
public class UserDaoImpl implements UserDao {
@Override
public int add(int a, int b) {
System.out.println("add方法执行了....");
return a + b;
}
@Override
public String update(String id) {
System.out.println("update方法执行了....");
return id;
}
}
使用Proxy类
package com.antherd.spring5;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class JDKProxy {
public static void main(String[] args) {
// 创建接口实现类代理对象
Class[] interfaces = {UserDao.class};
// Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// return null;
// }
// });
UserDaoImpl userDao = new UserDaoImpl();
UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
int result = dao.add(1, 2);
System.out.println(result);
}
}
// 创建代理对象代码
class UserDaoProxy implements InvocationHandler {
// 1 把创建的是谁的代理对象,把谁传递过来
// 有参构造
private Object obj;
public UserDaoProxy(Object obj) {
this.obj = obj;
}
// 增强的逻辑
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 方法之前
System.out.println("方法之前执行...." + method.getName()+ ":传递的参数...." + Arrays.toString(args));
// 被增强的方法执行
Object res = method.invoke(obj, args);
// 方法之后
System.out.println("方法之后执行...." + obj);
return res;
}
}
AOP操作(术语)
- 连接点:类里面哪些方法可以被增强,这些方法称为连接点
- 切入点:实际被真正增强的方法
- 通知(增强):实际增强的逻辑部分称为通知(增强)
通知有多种类型:
前置通知
后置通知
环绕通知
异常通知
最终通知:finally - 切面:是 动作
把通知应用到切入点过程
AOP操作(准备)
Spring框架一般都是基于AspectJ实现AOP操作
什么是AspectJ?
*
AspectJ不是Spring组成部分,独立AOP框架,一般把AspectJ和Spring框架一起使用,进行AOP操作
基于AspectJ实现AOP操作
(1)基于xml配置文件
(2)基于注解方式实现(使用)
在项目工程里引入AOP相关依赖
aspects
cglib 提取码: ry8u
aopalliance 提取码: tndu
aspectj.weaver 提取码: d6ga
切入点表达式
(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强
(2)语法结构:
execution([权限修饰符][返回类型][类全路径][方法名称] ([参数列表]))
举例1
:对com.antherd.dao.BookDao类里面的add进行增强
execution(* com.antherd.dao.BookDao.add(…))
举例2
:对com.antherd.dao.BookDao类里面的所有方法进行增强
execution( * com.antherd.dao.BookDao.*(…))
举例3
:对com.antherd.dao包里面的所有类,类里面所有方法进行增强
execution( * com.antherd.dao. *. *(…))
AOP操作(AspectJ注解)
-
创建类,在类里面添加增强方法
-
创建增强类(编写增强逻辑)
在增强类里面,创建方法,让不同方法代表不同通知类型 -
进行通知的配置
(1)在spring配置文件中,开启注解扫描
(2)使用注解创建User和UserProxy
(3)在增强类上面添加注解@Aspect
(4)在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: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 "> <!-- 开启注解扫描 --> <context:component-scan base-package="com.antherd.spring5.aopanno"></context:component-scan> <!-- 开启Aspect生成代理对象 --> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> </beans>
package com.antherd.spring5.aopanno; import org.springframework.stereotype.Component; // 被增强的类 @Component public class User { public void add() { System.out.println("add......"); } }
package com.antherd.spring5.aopanno; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; // 增强的类 @Component @Aspect // 生成代理对象 public class UserProxy { // 前置通知 public void before() { System.out.println("before......"); } }
-
配置不同类型的通知
在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置 UserProxy.before方法上添加如下:// @Before注解表示作为前置通知 @Before(value = "execution(* com.antherd.spring5.aopanno.User.add(..))")
-
测试
@Test public void testAopAnno() { ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); User user = context.getBean("user", User.class); user.add(); }
其他配置类型配置
// 前置通知 // @Before注解表示作为前置通知 @Before(value = "execution(* com.antherd.spring5.aopanno.User.add(..))") public void before() { System.out.println("before......"); } // 最终通知(发生异常也会执行) @After(value = "execution(* com.antherd.spring5.aopanno.User.add(..))") public void after() { System.out.println("after......"); } // 后置通知(返回通知,发生异常不会执行) @AfterReturning(value = "execution(* com.antherd.spring5.aopanno.User.add(..))") public void afterReturning() { System.out.println("afterReturning......"); } // 异常通知 @AfterThrowing(value = "execution(* com.antherd.spring5.aopanno.User.add(..))") public void afterThrowing() { System.out.println("afterThrowing......"); } @Around(value = "execution(* com.antherd.spring5.aopanno.User.add(..))") public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("环绕之前......"); // 被增强的方法执行 proceedingJoinPoint.proceed(); System.out.println("环绕之后......"); }
细节问题:
-
相同切入点抽取
// 相同切入点抽取 @Pointcut(value = "execution(* com.antherd.spring5.aopanno.User.add(..))") public void pointDemo() { } // 前置通知 // @Before注解表示作为前置通知 @Before(value = "pointDemo()") public void before() { System.out.println("before......"); }
-
有多个增强类同一个方法进行增强,设置增强类优先级
在增强类上面添加注解@Order(数字类型值),数字类型值越小优先级越高
AOP操作(AspectJ配置文件)
- 创建两个类,增强类和被增强类,创建方法
- 在spring配置文件中创建两个类对象
- 在spring配置文件中配置切入点
package com.antherd.spring5.aopxml;
public class Book {
public void buy() {
System.out.println("buy.......");
}
}
package com.antherd.spring5.aopxml;
public class BookProxy {
public void before() {
System.out.println("before......");
}
}
<?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.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="book" class="com.antherd.spring5.aopxml.Book"></bean>
<bean id="bookProxy" class="com.antherd.spring5.aopxml.BookProxy"></bean>
<!-- 配置aop增强 -->
<aop:config>
<!-- 切入点 -->
<aop:pointcut id="p" expression="execution(* com.antherd.spring5.aopxml.Book.buy(..))"/>
<!-- 切面 -->
<aop:aspect ref="bookProxy">
<!-- 配置增强作用在具体的方法上 -->
<aop:before method="before" pointcut-ref="p"/>
</aop:aspect>
</aop:config>
</beans>
测试
@Test
public void testAopXml() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
Book book = context.getBean("book", Book.class);
book.buy();
}
完全使用注解开发
创建配置类,不需要创建xml配置文件
package com.antherd.spring5.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan(basePackages = { "com.antherd"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigApp {
}