Spring框架学习笔记05:Spring AOP基础

本文详细介绍了如何在Spring中使用AOP,包括配置方式和注解方式。首先,展示了创建子包、任务类、骑士类、游吟诗人类以及配置文件的过程,解释了切点、切点表达式和切点函数的概念。接着,通过注解方式创建切面和配置,实现了方法拦截。最后,通过自定义注解增强了拦截功能,并展示了测试结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、采用配置方式使用AOP

(一)创建本讲所需子包

.在net.wzy.spring包里创建lesson05.aop_xml子包
在这里插入图片描述

(二)创建杀龙任务类在这里插入图片描述

package net.wzy.spring.lesson05.aop_xml;

import org.springframework.stereotype.Component;

@Component
public class SlayDragonQuest {
    public void embark() {
        System.out.println("执行杀龙任务。");
    }
}

(三)创建勇敢骑士类

在这里插入图片描述

package net.wzy.spring.lesson05.aop_xml;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BraveKnight {
    @Autowired
    private SlayDragonQuest slayDragonQuest;

    public void embarkOnQuest() {
        slayDragonQuest.embark();
    }
}

(四)创建游吟诗人类

.在aop_xml子包里创建游吟诗人类 - Minstrel
在这里插入图片描述

package net.wzy.spring.lesson05.aop_xml;

import org.springframework.stereotype.Component;


@Component
public class Minstrel {
    public void singBeforeQuest() {
        System.out.println("啦啦啦,骑士出发了!");
    }

    public void singAfterQuest() {
        System.out.println("真棒啊!骑士完成了任务!");
    }
}

(五)创建Spring配置文件

.在resources里创建aop_xml目录,在里面创建spring-config.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.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--组件扫描-->
    <context:component-scan base-package="net.wzy.spring.lesson05.aop_xml" />

    <!--AOP配置-->
    <aop:config>
        <!--定义切面-->
        <aop:aspect ref="minstrel">
            <!--定义切点-->
            <aop:pointcut id="embark" expression="execution(* net.wzy.spring.lesson05..*.embarkOnQuest(..))" />
            <!--声明前置通知-->
            <aop:before method="singBeforeQuest" pointcut-ref="embark"/>
            <!--声明后置通知-->
            <aop:after method="singAfterQuest" pointcut-ref="embark" />
        </aop:aspect>
    </aop:config>

</beans>

1、切点

在使用Spring框架配置AOP时,不管是通过XML配置文件还是注解方式,都需要定义pointcut(切点)。

2、切点表达式

. 拦截类里的指定方法:“execution(* net.hw.spring.lesson05….embarkOnQuest(…))"
. 拦截类里的所有方法:"execution(
net.hw.spring.lesson05….(…))”

3、切点函数

. execution()是最常用的切点函数,整个表达式可以分为五个部分。

. execution():表达式主体。
. 第一个*号:表示返回类型,号表示所有的类型。
. 包名:表示需要拦截的包名,后面的两个句点表示当前包和当前包的所有子包,. net.wzy.spring.lesson05包、子孙包下所有类的方法。
. 第二个
号:表示类名,*号表示所有的类。
. *(…):最后这个星号表示方法名,*号表示所有的方法,后面括弧里面表示方法的参数,两个句点表示任何参数。

(六)在pom文件里添加AOP相关依赖

在这里插入图片描述
.注意:添加新的依赖之后,记得更新

(七)创建测试类 - TestKnight

.在test/java里创建net.wzy.spring.lesson05.aop_xml包,在包里创建TestKnight
在这里插入图片描述

package net.wzy.spring.lesson05.aop_xml;

import net.wzy.spring.lesson05.aop_xml.BraveKnight;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class TestKnight {
    private ClassPathXmlApplicationContext context;

    @Before
    public void init() {
        // 基于Spring配置文件创建应用容器
        context = new ClassPathXmlApplicationContext("aop_xml/spring-config.xml");
    }

    @Test
    public void testBraveKnight() {
        // 根据名称从应用容器里获取勇敢骑士对象
        BraveKnight braveKnight = (BraveKnight) context.getBean("braveKnight");
        // 勇敢骑士执行任务
        braveKnight.embarkOnQuest();
    }
    @Test
    public void testDamselRescuingKnight(){

    }

    @After
    public void destroy() {
        // 关闭应用容器
        context.close();
    }
}


(八)运行测试方法testBraveKnight(),查看结果

在这里插入图片描述

二、采用注解方式使用AOP

(一)创建本讲所需子包

.在net.hw.spring包里创建lesson05.aop_annotation子包
在这里插入图片描述

(二)创建杀龙任务类

.在aop_annotation子包里创建杀龙任务类 - SlayDragonQuest
在这里插入图片描述

package net.wzy.spring.lesson05.aop_annotation;

import org.springframework.stereotype.Component;


@Component
public class SlayDragonQuest {
    public void embark() {
        System.out.println("执行杀龙任务。");
    }
}

(三)创建勇敢骑士类

.在aop_annotation子包里创建勇敢骑士类 - BraveKnight
在这里插入图片描述

package net.wzy.spring.lesson05.aop_annotation;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("Mike")
public class BraveKnight {
    @Autowired
    private SlayDragonQuest slayDragonQuest;

    public void embarkOnQuest() {
        slayDragonQuest.embark();
    }
}

(四)创建游吟诗人切面

.在aop_annotation子包里创建游吟诗人切面 - MinstrelAspect
在这里插入图片描述

package net.wzy.spring.lesson05.aop_annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 功能:游吟诗人切面
 * 作者:华卫
 * 日期:2021年03月29日
 */
@Aspect // 声明为切面
@Component // 交给Spring容器管理
public class MinstrelAspect {
    // 注解声明切点
    @Pointcut("execution(* net.wzy.spring.lesson05..*.embarkOnQuest(..))")
    public void embark() {
    }

    // 注解声明前置通知
    @Before("embark()")
    public void singBeforeQuest(JoinPoint joinPoint) {
        System.out.println("啦啦啦,骑士出发了!");
    }

    // 注解声明后置通知
    @After("embark()")
    public void singAfterQuest(JoinPoint joinPoint) {
        System.out.println("真棒啊!骑士完成了任务!");
    }
}

(五)创建Spring配置类

. 在aop_annotation子包里创建Spring配置类 - AopConfig
在这里插入图片描述

package net.wzy.spring.lesson05.aop_annotation;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;


@Configuration // 标明Spring配置类
@ComponentScan("net.wzy.spring.lesson05.aop_annotation") // 组件扫描
@EnableAspectJAutoProxy // 开启Spring对AspectJ的支持
public class AopConfig {
}

(六)创建骑士测试类

在这里插入图片描述

package net.wzy.spring.lesson05.aop_annotation;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class TestKnight {

    private AnnotationConfigApplicationContext context; // 基于注解配置类的应用容器

    @Before
    public void init() {
        // 基于注解配置类创建应用容器
        context = new AnnotationConfigApplicationContext(AopConfig.class);
    }

    @Test
    public void testBraveKnight() {
        // 根据名称从应用容器里获取勇敢骑士对象
        BraveKnight knight = (BraveKnight) context.getBean("Mike");
        // 勇敢骑士执行任务
        knight.embarkOnQuest();
    }

    @After
    public void destroy() {
        // 关闭应用容器
        context.close();
    }
}

(七)运行测试方法testBraveKnight(),查看效果

在这里插入图片描述

三、实现注解式拦截

(一)拦截的含义

. 在某个方法被访问之前进行拦截,然后在方法执行之前或之后加入某些操作,其实就是AOP的一种实现策略。Spring提供拦截器(Interceptor),它通过动态拦截Action调用的对象,允许开发者定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。本案例,我们不用拦截器,学习注解式拦截。

(二)创建注解接口

.在aop_annotation子包里创建注解接口 - Action
在这里插入图片描述

package net.hw.spring.lesson05.aop_annotation;

import java.lang.annotation.*;


@Target(ElementType.METHOD) // 拦截目标 - 方法
@Retention(RetentionPolicy.RUNTIME) // 保留策略 - 运行时
@Documented // 注解文档化
public @interface Action {
    String name();
}

1、@Target({ElementType.TYPE}) 注解

.ElementType 这个枚举类型的常量提供了一个简单的分类:注解可能出现在Java程序中的语法位置(这些常量与元注解类型(@Target)一起指定在何处写入注解的合法位置)

2、 @Retention({RetentionPolicy.Runtime}) 注解

.RetentionPolicy这个枚举类型的常量描述保留注解的各种策略,它们与元注解(@Retention)一起指定注释要保留多长时间

3、@Documented注解

Documented注解表明这个注解是由 javadoc记录的,在默认情况下也有类似的记录工具。 如果一个类型声明被注解了文档化,它的注解成为公共API的一部分。

(三)修改勇敢骑士类

给embarkOnQuest()添加自定义注解Action,并设置其name属性
在这里插入图片描述




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("Mike")
public class BraveKnight {
    @Autowired
    private SlayDragonQuest slayDragonQuest;

    @Action(name = "动作拦截器")
    public void embarkOnQuest() {
        slayDragonQuest.embark();
    }
}


(四)修改游吟诗人切面

在这里插入图片描述

(五)运行测试方法testBraveKnight(),查看效果在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值