Spring AOP is good enough to accomplish your requirement.
This is an small example to give you an idea: There are two classes and each one have three methods in common: play(), addPlayer() and gameover(), and each time that the play method is called the program have to call a routine to print a text, with AOP you don't need to repeat the same code.
For organization order I will use an interface, it is not mandatory but it's a good practice:
Game Interface:
public interface Game {
void play();
void addPlayer(String name);
void gameOver();
}
A soccer class that implements Game
public class Soccer implements Game {
@Override
public void play() {
System.out.println("Soccer Play started");
}
@Override
public void addPlayer(String name) {
System.out.println("New Soccer Player added:" + name);
}
@Override
public void gameOver() {
System.out.println("This soccer Game is Over");
}
}
A Baseball class that implements Game
public class Baseball implements Game {
@Override
public void play() {
System.out.println("Baseball game started at " + new Date());
}
@Override
public void addPlayer(String name) {
System.out.println("New Baseball Player added: " +name);
}
@Override
public void gameOver() {
System.out.println("The game is over");
}
}
Now the Aspect configuration to catch when the play method is called
@Aspect
@Component
public class AspectConfiguration {
@Before("execution(* org.boot.aop.aopapp.interfaces.Game.play(..))")
public void callBefore(JoinPoint joinPoint){
System.out.println("Do this allways");
System.out.println("Method executed: " + joinPoint.getSignature().getName());
System.out.println("******");
}
}
The @Before
annotation means that the method will be called before play method is executed. Also you need to specify a pointcut expression the tell Aspect how to match the method call that you need to trigger. For example in this case we use the play method and it is the pointcut expression: "execution(* org.boot.aop.aopapp.interfaces.Game.play(..))"
And finally the Spring Boot Application Class:
@EnableAspectJAutoProxy
@SpringBootApplication
public class AopappApplication {
public static void main(String[] args) {
Game soccer=null;
Game baseball=null;
AnnotationConfigApplicationContext ctx = (AnnotationConfigApplicationContext) SpringApplication.run(AopappApplication.class, args);
soccer = (Game) ctx.getBean("soccer");
baseball = (Game) ctx.getBean("baseball");
soccer.play();
baseball.play();
soccer.addPlayer("Player 1");
soccer.addPlayer("Player 2");
baseball.addPlayer("Player 23");
soccer.gameOver();
baseball.gameOver();
}
@Bean("soccer")
public Game soccer(){
return new Soccer();
}
@Bean("baseball")
public Game baseball(){
return new Baseball();
}
}
There is a god documentation about Spring AOP plese see the following link. Spring AOP Doc.