Aspect Oriented Programming : to avoid cross cutting concerns
AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does this by adding additional behaviour to existing code without modifying the code itself.
What are cross cutting concerns
let's say you want to log a message or perform execution on certain functionality like authentication before the execution of methods of same class, instead of declaring the functionality again and again for each methods.
Example
// dependencies<dependency><groupId>org.aspectj</groupId><artifactId>aspectjrt</artifactId><version>1.9.19</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.19</version></dependency>// definitionpublicvoidcheckout(String status) {System.out.println("checkout method of shopping cart called");}publicintquantity() {return2;}// callShoppingCart cart =context.getBean(ShoppingCart.class);cart.checkout("cancelled");// aspectj config@Configuration@ComponentScan(basePackages ="demo")@EnableAspectJAutoProxypublicclassBeanConfig {}// another class@Aspect@ComponentpublicclassLoggingAspect {// logging will not match if parameters not match// to match add .. in brackets// before execution @Before("execution(* demo.ShoppingCart.checkout(..))")publicvoidbeforeLogger(JoinPoint jp) {System.out.println(jp.getSignature());String arg =jp.getArgs()[0].toString();System.out.println("Before Loggers "+ arg); }// after execution @After("execution(* *.*.checkout(..))")publicvoidafterLogger() {System.out.println("After Loggers"); } @Pointcut("execution(* demo.ShoppingCart.quantity(..))")publicvoidafterReturningPointCut() { } @AfterReturning(pointcut ="afterReturningPointCut()", returning ="retVal")publicvoidafterReturning(String retVal) {System.out.println("after returning "+ retVal); }}@Aspect@ComponentpublicclassAuthenticationAspect { @Pointcut("within(demo..*)")publicvoidauthenticatingPointCut() { } @Pointcut("within(demo..*)")publicvoidauthorizingPointCut() { } @Before("authenticatingPointCut() || authorizingPointCut()")publicvoidauthenticate() {System.out.println("authenticating the request"); }}