当前位置: 首页 > news >正文

Spring-06 Xml和注解方式配置Aop

文章目录

  • 基本环境准备
    • 导入依赖
    • 添加xml 新约束
    • Spring的 五种通知类型
  • XML 方式配置AOP
    • 根据五种通知类型 配置增强类
    • xml配置
    • 测试
  • 基于注解方式配置 AOP
    • 核心配置文件扫描目标类和增强类所在包
    • 目标类添加注解
    • 增强类配置(切面)
      • 切入点表达式
      • 其他注解
      • 测试

基本环境准备

导入依赖

<!-- https://mvnrepository.com/artifact/aspectj/aspectjrt -->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjrt</artifactId>
  <version>1.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.6</version>
</dependency>

添加xml 新约束

在 spring 核心配置文件中添加 aop 约束

<?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">
	
</beans>

Spring的 五种通知类型

通知类型标签标签
前置通知aop:before目标方法执行前增强
后置通知aop:after目标方法执行后增强
环绕通知aop:around目标方法执行前后都增强
返回通知aop:after-returning目标方法成功执行之后调用
异常通知aop:after-throwing在目标方法抛出异常后调用

XML 方式配置AOP

根据五种通知类型 配置增强类

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class SelectAdvice {

    public void before(JoinPoint joinPoint){
        System.out.println("前置");
        System.out.println("目标类是: "+ joinPoint.getTarget());
        System.out.println("被织入的目标类方法为: "+ joinPoint.getSignature().getName());
    }

    public void afterReturning(){
        System.out.println("后置(方法不出现异常时调用! )");
    }

    public void around(ProceedingJoinPoint pjp) {
        System.out.println("环绕前置");
        try {
            // ProceedingJoinPoint 是joinpoint 的子接口, 用于执行目标方法, 确定在环绕通知中的位置
            pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("环绕后置");
    }

    public void exception(){
        System.out.println("异常通知");
    }

    public void after(){
        System.out.println("最终通知(类似于异常处理机制中的 finally)");
    }

}

xml配置

<!--配置目标类-->
<bean id="select" class="cn.Select"/>
<!--配置增强类(切面类)-->
<bean id="selectAdvice" class="cn.SelectAdvice"/>

<!-- 配置SpringAOP 增强 -->
<aop:config>
<!--     要对 哪些方法进行增强  -->
    <aop:pointcut id="abc" expression="execution(* cn..*.*(..))"/>
    <aop:pointcut id="def" expression="execution(* cn..*.update*(..))"/>
<!--    增强类的方法, 都对应那种增强方式    -->
    <aop:aspect ref="selectAdvice">
        <aop:before method="before" pointcut-ref="abc"/>
        <aop:after-returning method="afterReturning" pointcut-ref="abc"/>
        <aop:around method="around" pointcut-ref="abc"/>
        <aop:after-throwing method="exception" pointcut-ref="abc"/>
        <aop:after method="after" pointcut-ref="abc"/>
    </aop:aspect>
</aop:config>

测试

public static void main(String[] args) {
    ClassPathXmlApplicationContext app =
            new ClassPathXmlApplicationContext("classpath:application_context.xml");
    Select select =
            (Select)app.getBean("select");
    select.select();

}

基于注解方式配置 AOP

核心配置文件扫描目标类和增强类所在包

<!-- 使用注解配置 bean  -->
<context:component-scan base-package="cn.aop"/>
<!-- 加载 aop 的 注解 -->
<aop:aspectj-autoproxy/>

目标类添加注解

@Component

增强类配置(切面)

切入点表达式

// 声明增强类
@Aspect
@Component

@Pointcut("execution(* cn..*.select(..))")
    private void abc(){
    }

    @Pointcut("execution(* cn..*.update(..))")
    private void def(){
    }

其他注解

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SelectAdvice {
    @Pointcut("execution(* cn..*.select(..))")
    private void abc(){
    }

    @Pointcut("execution(* cn..*.update(..))")
    private void def(){
    }

    @Before("abc()")
    public void before(JoinPoint joinPoint){
        System.out.println("前置");
        System.out.println("目标类是: "+ joinPoint.getTarget());
        System.out.println("被织入的目标类方法为: "+ joinPoint.getSignature().getName());
    }

    @AfterReturning("abc()")
    public void afterReturning(){
        System.out.println("后置(方法不出现异常时调用! )");
    }

    @Around("abc()")
    public void around(ProceedingJoinPoint pjp) {
        System.out.println("环绕前置");
        try {
            // ProceedingJoinPoint 是joinpoint 的子接口, 用于执行目标方法, 确定在环绕通知中的位置
            pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("环绕后置");
    }

    @AfterThrowing("abc()")
    public void exception(){
        System.out.println("异常通知");
    }
    @After("abc()")
    public void after(){
        System.out.println("最终通知(类似于异常处理机制中的 finally)");
    }

}

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ={"classpath:application_context.xml"})
public class Test1 {

    @Autowired
    Select select;

    @Test
    public void aopTest(){
        select.add();
    }

}

相关文章:

  • 同步请求和异步请求(利用axios)
  • 猿创征文|瑞吉外卖——移动端_笔记
  • SpringBoot异常处理——异常显示的页面
  • 高等数学二从零开始学习的总结笔记(持续更新)
  • 无服务器学习01:基本概念+优点+面临的挑战
  • C#实验二
  • 熟悉c语言结构体
  • uboot源码分析(基于S5PV210)之启动第二阶段
  • 【分布式】分布式系统、Redis中间件 、Cache穿透、击穿、雪崩
  • Rust基础语法
  • 电子知识学习网站
  • 全站最简单 “数据滚动可视化大屏” 【JS基础拿来即用】
  • Vue项目实战——【基于 Vue3.x + Vant UI】实现一个多功能记账本(开发导航栏及公共部分)
  • ScalableViT网络模型
  • Nginx配置流数据转发指导
  •  D - 粉碎叛乱F - 其他起义
  • ECS应用管理最佳实践
  • EventListener原理
  • JavaScript HTML DOM
  • JavaScript新鲜事·第5期
  • PHP 小技巧
  • Python利用正则抓取网页内容保存到本地
  • Shell编程
  • TCP拥塞控制
  • tensorflow学习笔记3——MNIST应用篇
  • Vue 重置组件到初始状态
  • vue脚手架vue-cli
  • 从PHP迁移至Golang - 基础篇
  • 力扣(LeetCode)22
  • 使用 Docker 部署 Spring Boot项目
  • 我有几个粽子,和一个故事
  • 自动记录MySQL慢查询快照脚本
  • 策略 : 一文教你成为人工智能(AI)领域专家
  • 整理一些计算机基础知识!
  • !! 2.对十份论文和报告中的关于OpenCV和Android NDK开发的总结
  • (0)Nginx 功能特性
  • (32位汇编 五)mov/add/sub/and/or/xor/not
  • (Matalb回归预测)PSO-BP粒子群算法优化BP神经网络的多维回归预测
  • (第61天)多租户架构(CDB/PDB)
  • (非本人原创)史记·柴静列传(r4笔记第65天)
  • (附源码)ssm智慧社区管理系统 毕业设计 101635
  • (简单) HDU 2612 Find a way,BFS。
  • (原創) 未来三学期想要修的课 (日記)
  • (转)MVC3 类型“System.Web.Mvc.ModelClientValidationRule”同时存在
  • (转)Mysql的优化设置
  • . ./ bash dash source 这五种执行shell脚本方式 区别
  • .net core 6 集成 elasticsearch 并 使用分词器
  • .NET Core 网络数据采集 -- 使用AngleSharp做html解析
  • .Net Core/.Net6/.Net8 ,启动配置/Program.cs 配置
  • .NET delegate 委托 、 Event 事件
  • .net web项目 调用webService
  • .Net Winform开发笔记(一)
  • .NET使用存储过程实现对数据库的增删改查
  • /etc/sudoer文件配置简析
  • []C/C++读取串口接收到的数据程序