java 服务的任何公共方法的 AOP 切入点表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6861016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:37:34  来源:igfitidea点击:

AOP pointcut expression for any public method of a service

javaspringaopaspectjspring-aop

提问by Konrad Garus

What is the simplest pointcut expression that would intercept all public methods of all beans annotated with @Service? For instance, I expect it to affect both public methods of this bean:

什么是最简单的切入点表达式,它可以拦截所有用 注释的 bean 的所有公共方法@Service?例如,我希望它影响这个 bean 的两个公共方法:

@Service
public MyServiceImpl implements MyService {
    public String doThis() {...}
    public int doThat() {...}
    protected int doThatHelper() {...} // not wrapped
}

采纳答案by nicholas.hauschild

This documentationshould be extremely helpful.

文档应该非常有帮助。

I would do by creating two individual point cuts, one for all public methods, and one for all classes annotated with @Service, and then create a third one that combines the pointcut expressions of the other two.

我会创建两个单独的切入点,一个用于所有公共方法,一个用于所有用@Service 注释的类,然后创建第三个结合其他两个切入点表达式的切入点。

Take a look at (7.2.3.1 Supported Pointcut Designators) for which designators to use. I think you are after 'execution' designator for finding public methods, and the 'annotation' designator for finding your annotation.

看看 ( 7.2.3.1 Supported Pointcut Designators) 使用哪些指示符。我认为您在寻找公共方法的“执行”指示符和用于查找注释的“注释”指示符之后。

Then take a look at (7.2.3.2 Combining pointcut expressions) for combining them.

然后看一下(7.2.3.2 组合切入点表达式)来组合它们。

I have provided some code below (which I have nottested). It is mostly taken from the documentation.

我在下面提供了一些代码(我没有测试过)。它主要取自文档。

@Pointcut("execution(public * *(..))") //this should work for the public pointcut
private void anyPublicOperation() {}

//@Pointcut("@annotation(Service)") this might still work, but try 'within' instead
@Pointcut("@within(Service)") //this should work for the annotation service pointcut
private void inTrading() {}

@Pointcut("anyPublicOperation() && inTrading()")
private void tradingOperation() {}