springboot 使用自定义的aspect的示例代码

发布时间:2020-09-17 12:45:49 作者:张占岭
来源:脚本之家 阅读:231

对某个类型中的方法进行拦截,然后加入固定的业务逻辑,这是AOP面向切面编程可以做的事,在springboot里实现aop的方法也有很多, spring-boot-starter-aop 或者 aspectjweaver 都是可以实现的,不过我们在实现之前,先来看一下aop里的几个概念。

概念

实现

1 引用依赖包

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

2 添加切面和拦截的行为

@Aspect
@Component
@Slf4j
public class TestAspect {

 /**
  * 对TestService类下面的所有方法拦截.
  */
 @Pointcut("execution(* com.lind.start.test.aop.TestService.*(..))")
 public void pointcut() {
 }

 //前置通知
 @Before("pointcut()")
 public void beforeMethod(JoinPoint joinPoint) {
  if (joinPoint.getArgs().length == 1 && joinPoint.getArgs()[0] instanceof User) {
   User user = (User) joinPoint.getArgs()[0];
   user.setUsername("aop赋值");
   log.info("调用了前置通知" + user.toString());
  }

 }

 //@After: 后置通知
 @After("pointcut()")
 public void afterMethod(JoinPoint joinPoint) {
  log.info("调用了后置通知");
 }

 //@AfterRunning: 返回通知 result为返回内容
 @AfterReturning(value = "pointcut()", returning = "result")
 public void afterReturningMethod(JoinPoint joinPoint, Object result) {
  log.info("调用了返回通知");
 }

 //@Around:环绕通知
 @Around("pointcut()")
 public Object Around(ProceedingJoinPoint pjp) throws Throwable {
  log.info("around执行方法之前");
  Object object = pjp.proceed();
  log.info("around执行方法之后--返回值:" + object);
  return object;
 }

}

3 调用及结果

@SpringBootTest
@RunWith(SpringRunner.class)
public class AopTest {
 @Autowired
 TestService testService;

 @Test
 public void test() {
  testService.print(new User());
 }
}

springboot 使用自定义的aspect的示例代码

总结

到此这篇关于springboot 使用自定义的aspect的示例代码的文章就介绍到这了,更多相关springboot自定义的aspect内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!

推荐阅读:
  1. SpringBoot入门十八,自定义注解的简单实现
  2. 如何在SpringBoot项目中使用AOP

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot aspect

上一篇:mongodb3.4集群搭建实战之高可用的分片+副本集

下一篇:使用IDEA创建SpringBoot项目的方法步骤

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》