[Spring]AOP概念扫盲与操作指南

本文介绍了Spring AOP的基本概念,包括连接点、切点、通知、切面等,并提供了AOP环境配置的步骤,包括动态代理模式、切点定义、通知类型。还通过实例展示了如何创建切面、配置切面以及使用环绕通知。最后提到了Spring配置文件中定义切面的方式和一个具体的切面类permApect。
摘要由CSDN通过智能技术生成

[Spring]AOP概念扫盲与操作指南

本文是于2020-4-25重构,将文章中关于Spring的理念介绍移至:

你一直在用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>

定义切面

  1. 创建一个类,在上加入@Aspect注解
  2. 在任意方法上加上切点注解@PointCut并配好execution属性(确定拦截目标)
  3. 定义前置通知并关联切点注解的方法
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-->
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值