Spring学习(十四)——SpringBoot AOP编程

对于SpringBoot的面向切面编程,和前面我们用Spring进行AOP编程基本上没有差别,非要说有些不一样的地方,有两点:首先依赖的名称不同,Spring有Spring的AOP依赖,SpringBoot有SpringBoot的AOP依赖;Spring的AOP编程可以用注解形式的,也可以用xml配置文件的形式,而SpringBoot只能用注解的形式。下面我们具体来说一下。

一、SpringBoot AOP依赖

    <!-- SpringBoot AOP -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>

二、编写切面类

切面类各注解和方法参数的基础用法参考下面案例:

package cool.gjh.aspect;

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

/**
 * 切面
 * <p>
 *     驾驶提醒类
 * </p>
 *
 * @author ACE_GJH
 */
@Aspect
@Component
public class DrivingNotes {

    @Pointcut("execution(public void cool.gjh.beans..*.drive())")
    public void driveSafety(){};

    @Before("driveSafety()")
    public void beforeDrive(JoinPoint joinPoint){
        System.out.println("出发前:检查好车辆");
    }

    @After("driveSafety()")
    public void afterDrive(JoinPoint joinPoint){
        System.out.println("停车后:停放好车辆");
    }

    @Around(("driveSafety()"))
    public void aroundDriver(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("出发前请注意安全!!!");
        //放行方法
        joinPoint.proceed();
        System.out.println("到达后请注意安全!!!");
    }

}

三、编写测试类

package cool.gjh.aspect;

import cool.gjh.application.App;
import cool.gjh.beans.Car;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 测试SpringBoot面向切面编程
 *
 * @author ACE_GJH
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class AspectTest {

    @Autowired
    private Car car;

    /**
     * 测试依赖注入
     */
    @Test
    public void testInject(){
        car.drive();
    }

}

测试结果

测试结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭建華

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值