spring boot切面编程
使用@Aspect实现切面编程:
jar包依赖, spring依赖spring-aop和spring-aspects, @Aspect依赖aopalliance,aspectjweaver。
spring boot工程需要添加implementation 'org.springframework.boot:spring-boot-starter-aop'。
代码:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
@Aspect
public class AOPConfig {
@Around("@within(org.springframework.web.bind.annotation.RestController)")
public Object simpleAOP(final ProceedingJoinPoint pjp) throws Throwable {
try {
Object[] args = pjp.getArgs();
System.out.println("args: " + Arrays.asList(args));
Object o = pjp.proceed();
System.out.println("return: " + o);
return o;
} catch (Throwable e) {
throw e;
}
}
}
- 代码中
Object o = pjp.proceed();,在正常调用时,不需要添加args参数,在内部反射回调原函数时,会自动添加入参。 ProceedingJoinPoint同时提供了proceed(Object[] args)的方法,如果把代码替换为Object o = pjp.proceed(new String[]{"robin"});会替换原来的入参。

本文介绍了如何在Spring Boot中进行切面编程,包括所需的jar包依赖和工程配置。在代码示例中展示了如何实现切面,强调了在反射回调原函数时自动处理入参的特点,并提到了可以使用特定方法替换原有的入参。
1804

被折叠的 条评论
为什么被折叠?



