TCC分布式事务
1、springboot中使用AOP切面
1.1在pom.xml中增加 spring-boot-starter-aop 的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
1.2自定义注解
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.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SysLog { String value() default ""; }
1.2编写切面类,指定切入点并给切入点增加切点逻辑
切面类:类名随便取,类上添加@Aspect注解,注意一定要添加@Component注解
切入点:该方法为空方法即可,方法名随便取,方法上添加@Pointcut("@annotation(自定义注解的全类名)")
切点逻辑:可用@Before(切入点方法,带括号)、@After(切入点方法,带括号)、@Around(切入点方法,带括号),注意@Around方法具有参数和返回值
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.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect // 使用@Aspect注解声明一个切面 @Component public class SysLogAspect { @Pointcut("@annotation(com.fanghao.aspect.SysLog)") public void logPointCut() {} @After("logPointCut()") public void after() throws Throwable { System.out.println("后置"); } @Before("logPointCut()") public void before() throws Throwable { System.out.println("前置"); } @Around("logPointCut()") public Object around(ProceedingJoinPoint point) throws Throwable {
//此处也可从ProceedingJoinPoint中获取一些信息,如 添加自定义注解的方法名,参数,方法所在类的类名,自定义注解的一些属性等等 System.out.println("前环绕"); Object result = point.proceed(); System.out.println("后环绕"); return result; } }
1.3在需要横切的方法上添加自定义的切面注解
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @SysLog @GetMapping("/test") public String test(@RequestParam("name") String name){ System.out.println("正在测试......"); return name; } @GetMapping("/hello") public void hello(){ System.out.println("hello......"); } }
添加了自定义切面注解的方法才会触发切面功能,测试可看出,访问 /test 时启用了切面功能,访问 /hello 时则没有

浙公网安备 33010602011771号