AOP pointcut expression for any public method of a

2019-06-22 03:47发布

问题:

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:

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

回答1:

This documentation should 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.

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.

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

I have provided some code below (which I have not tested). 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() {}