aop - 如何仅在类型或方法注释上匹配一次
问题描述
我想要一个 Guice 拦截器来拦截对带注释的类或带注释的方法的调用。我希望能够将两者结合起来,即。使用具有不同属性的方法注释覆盖类注释。
我有这样的工作:
// Intercept all METHODS annotated with @MyAnnotation
bindInterceptor(
Matchers.any(),
Matchers.annotatedWith(company.MyAnnotation),
new TracingInterceptor());
// Intercept all methods in CLASSES annotated with @MyAnnotation
bindInterceptor(
Matchers.annotatedWith(company.MyAnnotation),
Matchers.any(),
new TracingInterceptor());
但是,当我这样注释类时:
@MyAnnotation
class MyClass {
@MyAnnotation
public void myMethod() {}
}
拦截器被调用两次,这很糟糕!
有什么方法可以避免触发拦截器两次,但行为相同?
解决方案
您可以通过使活页夹互斥来实现这一点,如下所示:
// Intercept all METHODS annotated with @MyAnnotation in classes not annotated with @MyAnnotation
bindInterceptor(
Matchers.not(Matchers.annotatedWith(company.MyAnnotation)),
Matchers.annotatedWith(company.MyAnnotation),
new TracingInterceptor());
// Intercept all methods not annotated with @MyAnnotation in CLASSES annotated with @MyAnnotation
bindInterceptor(
Matchers.annotatedWith(company.MyAnnotation),
Matchers.not(Matchers.annotatedWith(company.MyAnnotation)),
new TracingInterceptor());
// Intercept all METHODS not annotated with @MyAnnotation in CLASSES annotated with @MyAnnotation
bindInterceptor(
Matchers.annotatedWith(company.MyAnnotation),
Matchers.annotatedWith(company.MyAnnotation),
new TracingInterceptor());
推荐阅读
- javascript - 不同的 NodeJS HTTP 服务器端口有什么区别,我应该使用哪一个?
- mysql - JOIN 表,但将表名添加到列名以区分它们
- javascript - 如何使用 react 和 typescript 从一个子组件访问状态到另一个子组件?
- sql - 在带有 ORDER BY 的子选择中使用 JSON_ARRAYAGG 会出错
- html - thymeleaf 选择背景颜色
- r - 使用正则表达式从字符向量中提取文本
- javascript - 在javascript中自动滚动页面的一部分
- haskell - 如何解决:无法将类型“o”与“元素 mono0”匹配?
- android - MaterialCalenderView - 使选定的日期不可选
- python-3.x - 消息:过时的元素引用:使用 Selenium Python 单击网页上的多个链接时,元素未附加到页面文档