SpringBoot AOP的另一种实现方式 MethodInterceptor

462 阅读1分钟

摘要:本文主要介绍MethodInterceptor类的使用,它的作用和AOP编程一致,只是他是另一种实现方式,在此做一个记录;本文分为两块来测试,基于注解和基于execution

具体拦截器

public class AnyPrintInterceptor implements MethodInterceptor {

    private static final Logger log = LoggerFactory.getLogger(AnyPrintInterceptor.class);

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        log.info("任意拦截--开始");
        Object result = invocation.proceed();
        log.info("任意拦截--结束");
        return result;
    }
}

基于切面的配置

AnyPrint注解类

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnyPrint {

}

AnyPrintConfiguration配置类

@Configuration
public class AnyPrintConfiguration {

    @Bean
    public DefaultPointcutAdvisor anyPrintPointcutAdvisor(){
        AnyPrintInterceptor anyPrintInterceptor = new AnyPrintInterceptor();
        DefaultPointcutAdvisor defaultPointcutAdvisor = new DefaultPointcutAdvisor();
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("@annotation(com.github.huzhihui.currency.interceptor.AnyPrint)");
        defaultPointcutAdvisor.setPointcut(pointcut);
        defaultPointcutAdvisor.setAdvice(anyPrintInterceptor);
        return defaultPointcutAdvisor;
    }

}

Controller测试

@RestController
@RequestMapping(value = "any-print")
public class AnyPrintController {

    @Autowired
    private AnyPrintService anyPrintService;

    @AnyPrint
    @GetMapping("hello")
    public Object hello(){
        return "hello";
    }

    @GetMapping("hello-service")
    public Object helloService(){
        anyPrintService.hello();
        return "hello";
    }
}
  • curl http://127.0.0.1:8080/any-print/hello

image.png

execution实现

配置类

@Configuration
public class AnyPrintConfiguration {


    @Bean
    public DefaultPointcutAdvisor anyPrintPointcutAdvisor1(){
        AnyPrintInterceptor anyPrintInterceptor = new AnyPrintInterceptor();
        DefaultPointcutAdvisor defaultPointcutAdvisor = new DefaultPointcutAdvisor();
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* com.github.huzhihui.currency.service..*.*(..))");
        defaultPointcutAdvisor.setPointcut(pointcut);
        defaultPointcutAdvisor.setAdvice(anyPrintInterceptor);
        return defaultPointcutAdvisor;
    }


}

Service

@Service
public class AnyPrintService {

    private static final Logger log = LoggerFactory.getLogger(AnyPrintService.class);

    public void hello(){
        log.info("hello service");
    }
}

Controller测试类

@RestController
@RequestMapping(value = "any-print")
public class AnyPrintController {

    @Autowired
    private AnyPrintService anyPrintService;

    @GetMapping("hello-service")
    public Object helloService(){
        anyPrintService.hello();
        return "hello";
    }
}
  • curl http://127.0.0.1:8080/any-print/hello

image.png