0

I have two public methods in same class with same return type, only different is the argument it takes. I want to have a pointcut apply on only one of it.

Here is the example of the class:

public class HahaService{ public MyObject sayHaha(User user){ //do something } public MyObject sayHaha(Long id, User user){ //do something } } 

Now I want to have a pointcut only apply on the 2nd sayHaha method which takes two arguments: a Long id and a User user.

I currently have a @Pointcut

@Pointcut("execution(public MyObject com.abc.service.HahaService.sayHaha(..))") private void hahaPointCut() { } 

This pointcut is applied on both sayHaha method.

Is there a way I can do it only on the 2nd one?

1 Answer 1

2

Yes, just restrict your pointcut expression to methods that have specific parameter types.

Get rid of the .. and specify the parameter types

@Pointcut("execution(public MyObject com.example.HahaService.sayHaha(Long, com.example.User))") 

Alternatively, if you actually need the value of the arguments, you can use name binding to capture them. For example, your pointcut would be declared as

@Pointcut("execution(public MyObject com.example.HahaService.sayHaha(..)) && args(id, user)") private void hahaPointCut(Long id, User user) { } 

and the advice, for example a @Before, would be declared as (repeating the names)

@Before("hahaPointCut(id, user) ") public void before(Long id, User user) { /* execute advice */ } 

Now Spring AOP can determine the types of the parameters by the match between the parameters in the pointcut and the names used in args. It then matches those in @Before and binds to corresponding invocation arguments.

This technique is described in the chapter on Passing parameters to advice.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.