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