gpt4 book ai didi

spring-aop - 使用 Spring @Configuration 和 MethodInterceptor 拦截带注释的方法

转载 作者:行者123 更新时间:2023-12-05 00:32:07 29 4
gpt4 key购买 nike

我需要使用 spring-aop 拦截带注释的方法。
我已经有了拦截器,它实现了 AOP 联盟的 MethodInterceptor。

这是代码:

@Configuration
public class MyConfiguration {

// ...

@Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
// ...
}

public class MyInterceptor implements MethodInterceptor {

// ...

@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
//does some stuff
}
}

从我过去读到的内容来看,我可以使用 @SpringAdvice 注释来指定拦截器何时应该拦截某些东西,但现在已经不存在了。

谁能帮我?

非常感谢!

卢卡斯

最佳答案

MethodInterceptor可以通过注册 Advisor 来调用 bean 如下图。

@Configurable
@ComponentScan("com.package.to.scan")
public class AopAllianceApplicationContext {

@Bean
public Advisor advisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("@annotation(com.package.annotation.MyAnnotation)");
return new DefaultPointcutAdvisor(pointcut, new MyInterceptor());
}

}

关于spring-aop - 使用 Spring @Configuration 和 MethodInterceptor 拦截带注释的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13862216/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com