一. 点睛
AOP
是Spring
框架中的一个重要内容,在Spring
boot
里配置aop
非常简单,Spring
Boot
对AOP
的默认配置属性是开启的,也就是说spring.aop.auto
属性的值默认是true
,我们只要引入了AOP
依赖后,默认就已经增加了@EnableAspectJAutoProxy
功能,不需要我们在程序启动类上面加入注解@EnableAspectJAutoProxy
。
Spring
Aop
的相关内容可以参考前面的文章Spring4.x基础配置(三):Spring AOP
下面将使用Spring
Boot
通过模拟记录操作日志来演示基于注解拦截的AOP
实现方式。
二. 示例
1. 添加依赖
<!-- aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 编写拦截规则的注解
package org.light4j.springboot.aop.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
String value() default "";
}
(3). 在控制器的方法上使用注解@Action
package org.light4j.springboot.aop.controller;
import org.light4j.springboot.aop.annotation.Action;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/")
@Action("hello")
public String hello() {
return "Hello Spring Boot";
}
}
代码解释
@Action
注解加在方法hello()
上面。
(5). 编写切面
package org.light4j.springboot.aop.aspect;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
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.light4j.springboot.aop.annotation.Action;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogAspect {
// pointCut
@Pointcut("@annotation(org.light4j.springboot.aop.annotation.Action)")
public void log() {
}
/**
* 前置通知
*/
@Before("log()")
public void doBeforeController(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Action action = method.getAnnotation(Action.class);
System.out.println("action名称 " + action.value()); // ⑤
}
/**
* 后置通知
*/
@AfterReturning(pointcut = "log()", returning = "retValue")
public void doAfterController(JoinPoint joinPoint, Object retValue) {
System.out.println("retValue is:" + retValue);
}
}
代码解释
①通过
@Aspect
注解声明该类是一个切面。
②通过@Component
让此切面成为Spring
容器管理的Bean
。
③通过@Pointcut
注解声明切面。
④通过@After
注解声明一个建言,并使用@Pointcut
定义的切点。
⑤通过反射可以获得注解上面的属性,然后做日志记录相关的操作,下面的相同。
⑥通过@Before
注解声明一个建言,此建言直接使用拦截规则作为参数。
(6). 运行程序
启动程序,访问http://localhost:8080/,看到控制台打印如下日志:
三. 源代码示例:
公众号ID:longjiazuoA

未经允许不得转载:人生设计师 » Spring Boot核心(十):Spring Boot的AOP配置