Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept private annotated method with AOP

Tags:

java

aop

I have a custom annotation:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FeatureSwitch {

    String featureName();

}

I intercept this with the below aspect and use it to check if a feature is on or off. If the feature is off, then I throw an exception.

Aspect:

@Aspect
public class FeatureSwitchAspect {

    private final FeatureSwitchConfigurationApi featureSwitchConfigurationApi;

    public FeatureSwitchAspect(final FeatureSwitchConfigurationApi featureSwitchConfigurationApi) {
        this.featureSwitchConfigurationApi = featureSwitchConfigurationApi;
    }

    @Before("@annotation(featureSwitch)")
    public void checkFeatureSwitch(final FeatureSwitch featureSwitch) {
        final String featureName = featureSwitch.featureName();
        Boolean featSwitch = featureSwitchConfigurationApi.isFeatureActive(featureName);
        if (!featSwitch) {
            throw new FeatureSwitchOffException();
        }
    }
}

The problem I am having is that the behaviour seems inconsistent. This seems to do as expected when I call a method from a different class, but if I make a call to an annotated private method, no interception occurs. Have I got it configured incorrectly? Any suggestions would be appreciated.

like image 327
Ben Green Avatar asked Feb 05 '26 23:02

Ben Green


1 Answers

Method calls from within classes will not work with proxy-based AOP.

Since you are using the keyword this (which is a pointer to your original object and not the proxy objects that is wrapping it), you will be calling the wrapped method directly - thus bypassing the code added as a result of your AOP.

like image 138
StuPointerException Avatar answered Feb 08 '26 14:02

StuPointerException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!