Reputation: 23002
I have two advice classes which implement MethodInterceptor. I want to apply these advices to one pointcut express and choose advice when I call methods of target.
I think it's not possible so I made a subclass of target class and use pointcut express for subclass.
Classes looks like:
class SuperClass implements SomeInterface {
public int getZero() {
return 0;
}
}
class SubClass extends SuperClass implements SomeInterface {
}
And XML looks like:
<bean id="subAdvice" class="package.SomeAdvice" />
<aop:config>
<aop:advisor advice-ref="subAdvice" pointcut="execution(* *..SubClass.*(..))"/>
</aop:config>
But the subAdvice
is not applied when I called getZero()
method through SubClass
, maybe because there's no implemented methods in SubClass
. It worked when I override the getZero()
method but I don't want to override it because there's too many methods in actual SuperClass
and it's superfluous if I want to call SuperClass
's method.
Can I apply advice to subclass which doesn't implement methods? Or is there any other good way to apply advice selectively?
Upvotes: 1
Views: 1103
Reputation: 23002
I found out that my approach was wrong. I could apply the advice for just subclass with bean
express like this:
<bean id="subAdvice" class="package.SomeAdvice" />
<aop:config>
<aop:advisor advice-ref="subAdvice" pointcut="bean(subClass)"/>
</aop:config>
But I didn't need to make a subclass for that. What I needed is just one more bean to apply other advice. In conclusion, I can apply multiple advice by making multiple beans and choose advice selectively by bean name.
Upvotes: 0
Reputation: 11
Your theory about it not working because you didn't implement/override it in your subclass is right. Your pointcut specifies all executions of methods defined in the subclass, and without any methods actually defined in the class you won't have any matching join points.
I'm not sure from your question whether you want to match all of the subclass' method executions or only the ones defined on the superclass but called on an instance of the subclass. If you were asking about the former you might want to use this pointcut:
execution(* package.SuperClass+.*(..))
The added plus picks out all subtypes of SuperClass, so your pointcut now selects all executions of all methods defined in SuperClass or its subclasses. Check out the AspectJ reference here for more info on subtype patterns.
Upvotes: 1