Spring学习5——AOP

AOP

  • AOP(面向切面编程)是OOP(面向对象编程)的衍生和完善
  • AOP通过对业务逻辑的各个部分进行隔离,降低业务逻辑的耦合性,提高程序复用性和开发效率

案例:骑士执行任务前和执行任务后,游吟诗人唱赞歌

采用配置方式使用AOP

一、使用项目SpringDemo2021

链接:https://pan.baidu.com/s/1lsV9SniUIAZ-KN4IB9RUQA
提取码:j9vc

二、创建lesson05子包

在这里插入图片描述

三、创建杀龙任务类

![在这里插入图片描述](https://img-blog.csdnimg.cn/20210419193810541.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2RvdWJsZXZpZXc=,size_16,color_FFFFFF,t_70

package net.lj.spring.lesson05;

import org.springframework.stereotype.Component;

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

四、创建勇敢骑士类

在这里插入图片描述

package net.lj.spring.lesson05;

/**
 * 功能:勇敢骑士类
 */

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();
    }
}

五、创建游吟诗人类

在这里插入图片描述

package net.lj.spring.lesson05;

import org.springframework.stereotype.Component;

/**
 * 游吟诗人类
 */
@Component
public class Minstrel {
    public void singBeforeQuest() {
        System.out.println("啦啦啦,骑士出发了!");
    }

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

六、创建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 
       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.lj.spring.lesson05"/>

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

七、在pom文件里添加AOP相关依赖

<!--Spring AOP-->                                         
<dependency>                                              
    <groupId>org.springframework</groupId>                
    <artifactId>spring-aop</artifactId>                   
    <version>${spring.version}</version>                  
</dependency>                                             
<!--AspectJ支持-->                                          
<dependency>                                              
    <groupId>aspectj</groupId>                            
    <artifactId>aspectjrt</artifactId>                    
    <version>1.5.4</version>                              
</dependency>                                             
<dependency>                                              
    <groupId>org.aspectj</groupId>                        
    <artifactId>aspectjweaver</artifactId>                
    <version>1.9.6</version>                              
    <scope>runtime</scope>                                
</dependency>              

八、创建测试类

在这里插入图片描述

package net.lj.spring.lesson05;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试骑士类
 */
public class TestKnight {

    private ClassPathXmlApplicationContext context; // 基于类路径XML配置文件的应用容器

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

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

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

运行测试

在这里插入图片描述

采用注解方式使用AOP

一、创建子包

在这里插入图片描述

二、创建杀龙任务

在这里插入图片描述

package net.lj.spring.lesson0502;

import org.springframework.stereotype.Component;

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

三、创建勇敢骑士类

在这里插入图片描述

package net.lj.spring.lesson0502;

/**
 * 勇敢骑士类
 */

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();
    }
}

四、创建游吟诗人切面

在这里插入图片描述

package net.lj.spring.lesson0502;

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;

/**
 * 游吟诗人切面
 */
@Aspect // 声明为切面
@Component // 交给Spring容器管理
public class MinstrelAspect {
    // 注解声明切点
    @Pointcut("execution(* net.lj.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配置类

在这里插入图片描述

package net.lj.spring.lesson0502;

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

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

六、创建骑士测试类

在这里插入图片描述

package net.lj.spring.lesson0502;

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();
    }
}

七、运行测试

在这里插入图片描述

注解式拦截

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

一、创建注解接口

在这里插入图片描述

package net.lj.spring.lesson0502;

import java.lang.annotation.*;

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

二、修改勇敢骑士类

在这里插入图片描述

三、修改游吟诗人切面

在这里插入图片描述

package net.lj.spring.lesson0502;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

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

    // 注解声明前置通知
    @Before("embark()")
    public void singBeforeQuest(JoinPoint joinPoint) {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取被拦截的方法
        Method method = signature.getMethod();
        // 获取注解式拦截
        Action action = method.getAnnotation(Action.class);
        // 提示用户被拦截了
        System.out.println("[" + action.name() + "]拦截了[" + method.getName() + "]:拦截前!");
        System.out.println("啦啦啦,骑士出发了!");
    }

    // 注解声明后置通知
    @After("embark()")
    public void singAfterQuest(JoinPoint joinPoint) {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取被拦截的方法
        Method method = signature.getMethod();
        // 获取注解式拦截
        Action action = method.getAnnotation(Action.class);
        // 提示用户被拦截了
        System.out.println("[" + action.name() + "]拦截了[" + method.getName() + "]:拦截后!");
        System.out.println("真棒啊!骑士完成了任务!");
    }
}

四、运行测试

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值