user3663882
user3663882

Reputation: 7357

Is it possible to intercept any call to a method of a class?

In our project we're using Spring Framework and now I need to intercept any method call to any object method. Does Spring provide such a facility? I mean, for instance we have a method:

public void m(){
    MyClass a = new MyClass();
    a.method(); //I need to intercept that method call and invoke some stuff
}

Is such a thing possible?

Upvotes: 3

Views: 1624

Answers (2)

Arek
Arek

Reputation: 3176

Yes, it's possible - you'll need to use AOP. If you want to intercept every call of a method from spring managed bean then Spring AOP java proxying will be sufficient. Otherwise you'll need to use AspectJ.

Upvotes: 3

davioooh
davioooh

Reputation: 24666

You need to include Spring AOP in you project.

An option to intercept any call for methods defined in MyClass is:

@Around("* my.application.MyClass.*(..)")
public Object interceptAnyMethodCall(ProceedingJoinPoint pjp) throws Throwable {

    Object retVal = pjp.proceed();

    // ... your code

    return retVal;
}

Upvotes: 1

Related Questions