AOP
AOP概念
- 面向切面编程(方面),利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得 业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率
- 通俗描述:不通过修改源代码方式,在主干功能里面添加新功能
例子图解:
AOP底层原理
AOP 底层原理使用动态代理
动态代理有两种:
- 有接口情况,使用 JDK 动态代理
- 没有接口情况,使用 CGLIB 动态代理
AOP底层原理(JDK动态代理代码实现)
说明
- 使用 JDK 动态代理,使用 Proxy 类里面的方法创建代理对象
- 调用 newProxyInstance 方法
第一参数,类加载器
第二参数,增强方法所在的类,这个类实现的接口,支持多个接口
第三参数,实现这个接口 InvocationHandler,创建代理对象,写增强的部分
代码实现
- 创建接口,定义方法
/**
* @author cVzhanshi
* @create 2021-04-16 15:42
*/
public interface UserDao {
int add(int a,int b);
String update(String id);
}
- 创建接口实现类,实现方法
/**
* @author cVzhanshi
* @create 2021-04-16 15:42
*/
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 类创建接口代理对象
/**
* @author cVzhanshi
* @create 2021-04-16 15:44
*/
public class JDKProxyTest {
public static void main(String[] args) {
//创建接口实现类代理对象
Class[] interfaces = {UserDao.class};
//方式一 :匿名内部类
// Proxy.newProxyInstance(JDKProxyTest.class.getClassLoader(), interfaces,new InvocationHandler() {
// @Override
// public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
// return null;
// }
// });
//
UserDaoImpl userDao = new UserDaoImpl();
//方式二: new一个实现InvocationHandler的类传入参数
UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxyTest.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
System.out.println(dao.add(10, 20));
System.out.println("---------------------------------------------");
System.out.println(dao.update("cVzhanshi"));
}
}
class UserDaoProxy implements InvocationHandler{
// 把创建的是谁的代理对象,把谁传递过来
//有参数构造传递 有利于方法的调用
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;
}
}
- 运行效果:
- 补充
运用小技巧,在增强的逻辑中对不同的方法,进行不同的增强
//增强的逻辑
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("add".equals(method.getName())){
//add方法的增强
}else if("update".equals(method.getName())){
//update方法的增强
}
}
AOP(术语)
- 连接点
类里面能被增强的方法称为连接点
- 切入点
实际被真正增强的方法称为切入点
- 通知(增强)
实际增强的逻辑部分 例如,登录的权限管理
通知有多种类型
前置通知(增强逻辑在方法之前)
后置通知(增强逻辑在方法之后)
环绕通知(增强逻辑在方法前后都有)
异常通知(增强逻辑在方法有异常时执行)
最终通知(finally中)
- 切面
是一种动作,把通知应用到切入点的过程
AOP操作
操作准备
Spring 框架一般都是基于 AspectJ 实现 AOP 操作 ,其中 AspectJ 不是 Spring 组成部分,独立 AOP 框架,一般把 AspectJ 和 Spirng 框架一起使 用,进行 AOP 操作
基于 AspectJ 实现 AOP 操作 有两种
- 基于 xml 配置文件实现
- 基于注解方式实现
在项目工程里面引入 AOP 相关依赖
切入点表达式
切入点表达式作用:知道对哪个类里面的哪个方法进行增强
语法结构: execution(
[权限修饰符
] [返回类型][类全路径
][方法名称
][参数列表]) )
案例:
举例 1:对 com.atguigu.dao.BookDao 类里面的 add 进行增强
execution(* com.atguigu.dao.BookDao.add(..))
举例 2:对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强
execution(* com.atguigu.dao.BookDao.* (..))
举例 3:对 com.atguigu.dao 包里面所有类,类里面所有方法进行增强
execution(* com.atguigu.dao.*.* (..))
AOP 操作(AspectJ 注解)
@Before ----> 前置通知
@AfterReturning ------> 后置通知(返回通知) ----> 有异常不会运行
@After -----> 最终通知
@AfterThrowing -----> 异常通知
@Around -----> 环绕通知
后面演示验证
- 创建类,在类里面定义方法
public class User {
public void add(){
System.out.println("----------------add-----------------");
}
}
- 创建增强类(编写增强逻辑) 在增强类里面,创建方法,让不同方法代表不同通知类型
/**
* @author cVzhanshi
* @create 2021-04-16 19:27
*/
public class UserProxy {
//前置通知
public void before() {
System.out.println("before.........");
}
//后置通知(返回通知)
public void afterReturning() {
System.out.println("afterReturning.........");
}
//最终通知
public void after() {
System.out.println("after.........");
}
//异常通知
public void afterThrowing() {
System.out.println("afterThrowing.........");
}
//环绕通知
public void around(ProceedingJoinPoint proceedingJoinPoint) throws
Throwable {
System.out.println("环绕之前.........");
//被增强的方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕之后.........");
}
}
-
进行通知的配置
-
在 spring 配置文件中,开启注解扫描
添加context和aop命名空间
<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.atguigu.anno"></context:component-scan>
</beans>
- 使用注解创建 User 和 UserProxy 对象
@Component
public class UserProxy {}
@Component
public class User {}
- 在增强类上面添加注解 @Aspect
@Component
@Aspect
public class UserProxy {}
- 在 spring 配置文件中开启生成代理对象
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
- 配置不同类型的通知 ,在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置
/**
* @author cVzhanshi
* @create 2021-04-16 19:27
*/
@Component
@Aspect
public class UserProxy {
//前置通知
//@Before 注解表示作为前置通知
@Before(value = "execution(* com.atguigu.anno.User.add(..))")
public void before() {
System.out.println("before.........");
}
//后置通知(返回通知)
@AfterReturning(value = "execution(* com.atguigu.anno.User.add(..))")
public void afterReturning() {
System.out.println("afterReturning.........");
}
//最终通知
@After(value = "execution(* com.atguigu.anno.User.add(..))")
public void after() {
System.out.println("after.........");
}
//异常通知
@AfterThrowing(value = "execution(* com.atguigu.anno.User.add(..))")
public void afterThrowing() {
System.out.println("afterThrowing.........");
}
//环绕通知
@Around(value = "execution(* com.atguigu.anno.User.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws
Throwable {
System.out.println("环绕之前.........");
//被增强的方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕之后.........");
}
}
- 测试
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
User user = context.getBean("user", User.class);
user.add();
}
- 运行效果(无异常):
- 运行效果(有异常):
由此可知:
@Before ----> 前置通知
@AfterReturning ------> 后置通知(返回通知) ----> 有异常不会运行
@After -----> 最终通知
@AfterThrowing -----> 异常通知
@Around -----> 环绕通知
补充
- 相同的切入点抽取
当使用的切入点表达式有很多相同时,可以进行相同切入点抽取
/**
* @author cVzhanshi
* @create 2021-04-16 19:27
*/
@Component
@Aspect
public class UserProxy {
//相同切入点抽取
@Pointcut(value = "execution(* com.atguigu.anno.User.add(..))")
public void pointdemo() {
}
//前置通知
//@Before 注解表示作为前置通知
@Before(value = "pointdemo()")
public void before() {
System.out.println("before.........");
}
//后置通知(返回通知)
@AfterReturning(value = "pointdemo()")
public void afterReturning() {
System.out.println("afterReturning.........");
}
//最终通知
@After(value = "pointdemo()")
public void after() {
System.out.println("after.........");
}
//异常通知
@AfterThrowing(value = "pointdemo()")
public void afterThrowing() {
System.out.println("afterThrowing.........");
}
//环绕通知
@Around(value = "pointdemo()")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws
Throwable {
System.out.println("环绕之前.........");
//被增强的方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕之后.........");
}
}
- 有多个增强类多同一个方法进行增强,设置增强类优先级
在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高
@Component
@Aspect
@Order(1)
public class PersonProxy {
//相同切入点抽取
@Pointcut(value = "execution(* com.atguigu.anno.User.add(..))")
public void pointdemo() {
}
@Before(value = "pointdemo()")
public void before() {
System.out.println("before Person ---- 1.........");
}
}
@Component
@Aspect
@Order(3)
public class UserProxy {
//相同切入点抽取
@Pointcut(value = "execution(* com.atguigu.anno.User.add(..))")
public void pointdemo() {
}
//前置通知
//@Before 注解表示作为前置通知
@Before(value = "pointdemo()")
public void before() {
System.out.println("before UserProxy ---- 3.........");
}
}
运行效果:
- 完全使用注解开发
创建配置类,不需要创建 xml 配置文件
@Configuration
@ComponentScan(basePackages = {"com.atguigu.anno"}) //开启扫描注解
@EnableAspectJAutoProxy(proxyTargetClass = true) //开启生成代理对象
public class ConfigAop {
}
相当于:
<context:component-scan base-package="com.atguigu.anno"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
AOP 操作(AspectJ 配置文件)
-
创建两个类,增强类和被增强类,创建方法
-
在 spring 配置文件中创建两个类对象
- 在 spring 配置文件中配置切入点
~~~xml
<!--配置 aop 增强-->
<aop:config>
<!--切入点-->
<aop:pointcut id="p"expression="execution(*com.atguigu.spring5.aopxml.Book.buy(..))"/>
<!--配置切面-->
<aop:aspect ref="bookProxy">
<!--增强作用在具体的方法上-->
<aop:before method="before" pointcut-ref="p"/>
</aop:aspect>
</aop:config>