Spring Boot项目引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
package pers.wmx.springbootfreemarkerdemo.aspect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author: wangmingxin03
* @date: 2020-09-02
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionAspect {
String value() default "";
}
package pers.wmx.springbootfreemarkerdemo.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
/**
* @author: wangmingxin03
* @date: 2020-09-02
*/
@Aspect
@Component
@Lazy
public class MyAspect {
//切面
@Pointcut("@annotation(pers.wmx.springbootfreemarkerdemo.aspect.ActionAspect)")
public void access() {
}
//环绕
@Before("access()")
public void doBefore() {
System.out.println("do before");
}
//环绕
@Around("access() && @annotation(actionAspect)")
public Object doAround(ProceedingJoinPoint joinPoint, ActionAspect actionAspect) throws Throwable {
System.out.println(actionAspect.value());
//do something
Object result = joinPoint.proceed();
System.out.println(result);
return result;
}
}
@Around("access() && @annotation(actionAspect)")
这样可以拿到注解里的值
@ActionAspect(value = "do aspect")
@RequestMapping("/response/test")
@ResponseBody
public User testResponse1(){
User user = new User();
user.setUserName("xinye");
user.setDescription("shuaiqi");
return user;
}
调接口输出:
do aspect
do before
pers.wmx.springbootfreemarkerdemo.entity.User@61e35138
通过切面编程往往可以达到很多奇效
有时候想做一些全局的前置和后置处理,可以尝试搞搞,通过自定义注解比较灵活
转载请注明:汪明鑫的个人博客 » Spring Boot 自定义注解实现切面编程
说点什么
您将是第一位评论人!