Faizan Mohammad
Faizan Mohammad

Reputation: 33

What is the use case of skipping method execution in around advice?

I understood what @Around Advice does, and when we need to share Before and after state then we can use it, and we call also skip method execution. My question is why Spring given us this power to skip method execution and what is the use case of skipping method?

Upvotes: 0

Views: 817

Answers (2)

kriegaex
kriegaex

Reputation: 67317

Side effects as Nándor said are one thing. Maybe you even want to replace the return value altogether, possibly because there is a bug in a class you do not have the source code of or for other reasons:

Buggy Java class:

package de.scrum_master.app;

public class Earth {
    public String getShape() {
        return "disc";
    }
}

Driver application:

package de.scrum_master.app;

public class Application {
    public static void main(String[] args) {
        System.out.println("The Earth is a " + new Earth().getShape() + ".");
    }
}

Console log:

The Earth is a disc.

Bugfix aspect:

package de.scrum_master.aspect;

import de.scrum_master.app.Earth;

public aspect BugfixAspect {
    String around() : execution(* Earth.getShape()) {
        return "sphere";
    }
}

Console log with aspect applied:

The Earth is a sphere.

Upvotes: 1

Nándor Előd Fekete
Nándor Előd Fekete

Reputation: 7098

Method calls usually have side effects. Whenever you decide in your aspect that those side effects are undesirable for whatever reason, it's a valid use case to skip executing the original execution. This includes use cases for caching for example, when the side effects are not in terms of data, but execution time.

Upvotes: 0

Related Questions