摘要:本文主要介绍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
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