springboot 面向切面编程

springboot 面向切面编程

  • 1. 导入依赖
  • 2. 通知 class
  • 3. 测试输出

1. 导入依赖


	org.springframework.boot
	spring-boot-starter-aop		

2. 通知 class

package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class MyAspect {

	@Before(value = "within(com.example.demo.service.*Impl)")
	public void before(JoinPoint point) {
		log.info("=======前置通知======");
		log.info("当前执行方法名 >>> " + point.getSignature().getName());
		log.info("目标对象 >>> " + point.getTarget());
	}

	@After(value = "within(com.example.demo.service.*Impl)")
	public void after(JoinPoint point) {
		log.info("=======后置通知======");
		log.info("当前执行方法名 >>> " + point.getSignature().getName());
		log.info("目标对象 >>> " + point.getTarget());
	}

	@Around(value = "within(com.example.demo.service.*Impl)")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		log.info("=======执行方法前进入环绕通知======");
		log.info("当前执行方法名 >>> " + point.getSignature().getName());
		log.info("目标对象 >>> " + point.getTarget());
		Object object = point.proceed();

		log.info("=======执行方法后进入环绕通知======");
		return object;
	}
}

3. 测试输出

=======执行方法前进入环绕通知======                                  
当前执行方法名 >>> test                                          
目标对象 >>> com.example.demo.service.AdviceTestImpl@76b0ae1b 
=======前置通知======                                         
当前执行方法名 >>> test                                          
目标对象 >>> com.example.demo.service.AdviceTestImpl@76b0ae1b 
测试方法                                                      
=======执行方法后进入环绕通知======                                  
=======后置通知======                                         
当前执行方法名 >>> test                                          
目标对象 >>> com.example.demo.service.AdviceTestImpl@76b0ae1b 

你可能感兴趣的:(springboot)