Recently, I was exploring various logging mechanism available in Java and I came across this topic – Aspectj.
I found the AOP – Aspect Oriented Programming approach quite unique (and quite complex to use as well!)
As I learned basics of Aspectj step by step, I kept taking notes of whatever I’ve grasped. Sharing it here.
What is AOP?
AOP is a programming paradigm. It breaks the program logic into distinct parts (called concerns). It is used to increase modularity by cross-cutting concerns.
Aspect Oriented Programming (AOP) compliments OOPs in the sense that it also provides modularity. But the key unit of modularity is aspect than class.
A cross-cutting concern is a concern that can affect the whole application and should be centralized in one location in code as possible, such as transaction management, authentication, logging, security etc.
Implementation of AOP results into well-modularized implementation of cross cutting concerns.
Why AOP?
It provides the pluggable way to dynamically add the additional concern before, after or around the actual logic. Suppose there are 10 methods in a class as given below:
class A{ public void m1(){...} public void m2(){...} public void m3(){...} public void m4(){...} public void m5(){...} public void n1(){...} public void n2(){...} public void p1(){...} public void p2(){...} public void p3(){...} }
There are 5 methods that starts from m, 2 methods that starts from n and 3 methods that starts from p.
Understanding Scenario
I have to maintain log and send notification after calling methods that starts from m.
Problem without AOP
We can call methods (that maintains log and sends notification) from the methods starting with m. In such scenario, we need to write the code in all the 5 methods.
But, if client says in future, I don’t have to send notification, you need to change all the methods. It leads to the maintenance problem.
Solution with AOP
We don’t have to call methods from the method. Now we can define the additional concern like maintaining log, sending notification etc. in the method of a class. Its entry is given in the xml file.
In future, if client says to remove the notifier functionality, we need to change only in the xml file. So, maintenance is easy in AOP.
Where use AOP?
AOP is mostly used in following cases:
– To provide declarative enterprise services such as declarative transaction management.
– It allows users to implement custom aspects.
AOP Concepts and Terminology
AOP concepts and terminologies are as follows:
- Join point
- Advice
- Pointcut
- Introduction
- Target Object
- Aspect
- Interceptor
- AOP Proxy
- Weaving
- Cross-cutting concerns
Cross-cutting concerns
Part of logic that spans across entire application. It affects entire application. Such as logging or session mechanism.
Join point
Join point is any point in your program such as method execution, exception handling, field access etc.
Advice
Advice represents an action taken by an aspect at a particular join point. There are different types of advices:
- Before Advice: it executes before a join point.
- After Returning Advice: it executes after a joint point completes normally.
- After Throwing Advice: it executes if method exits by throwing an exception.
- After (finally) Advice: it executes after a join point regardless of join point exit whether normally or exceptional return.
- Around Advice: It executes before and after a join point.
Pointcut
It is an expression language of AOP that matches join points.
Aspect
It is a class that contains advices, joinpoints etc.
Sum up
A join point is a well-defined point in the program flow.
A pointcut picks out certain join points and values at those points.
A piece of advice is code that is executed when a join point is reached.
Aspects are the unit of modularity for crosscutting concerns. They behave somewhat like Java classes, but may also include pointcuts, advice and inter-type declarations.
AOP Implementations
AOP implementations are provided by:
- AspectJ
- Spring AOP
- JBoss AOP
Core concerns vs Cross cutting concerns
A core concern is a reason that the application exists, the business logic that the application automates. If you have a logistics application that handles shipping freight, figuring out how much cargo you can pack on a truck or what’s the best route for the truck to take to drop off its deliveries might be core concerns.
Cross-cutting concerns are typically implementation details that need to be kept separate from business logic.
Weaving / Aspect weaving
There are a few different ways to inject the AOP code in our application, but one common denominator is that they all require some type of extra step to be applied to our code. This extra step is called weaving.
Compile-time weaving
If you have both the source code of the aspect and the code that you are using aspects in, you can compile your source-code and the aspect directly with an AspectJ compiler.
Post-compile weaving / Binary weaving
If you can’t, or don’t want to use source-code transforms to weave the aspects into the code, you can take already compiled classes or jars and inject aspects.
Load-time weaving
Acts the same way as post-compile weaving / binary weaving but waits to inject aspects into the code until the class loader loads the class file. This requires one or more weaving class loaders.
AOP in Real Life
AOP(Aspect Oriented Programing) is not a technology or a product, its a programming paradigm.
Its one of the principles of DRY (Don’t Repeat Yourself).
The repeating thing here is the aspect or crosscutting concerns. In AOP, these aspects are extracted and then applied to target in a manageable and reusable way.
- Database transaction management
- Security check
- Logging
Not all loggings are cross cutting concerns. The loggings that specific to the business itself should stay with business code. But the system wide loggings for example, the method calling as a system event that should be logged is cross cutting concerns. - Spring has well implemented AOP framework already in place.
Java Example
Following can be the simplest example of using AOP via Aspectj in Java:
//Entry point of application public class TestAOP { public static void main(String[] args) { AOPDemo aspectjDemo = new AOPDemo(); aspectjDemo.testAspectj(); } } public class AOPDemo { //testAspectj() is our point of interest. So it will be our Join Point. public void testAspectj() { System.out.println("Testing Aspectj"); } } //This class is Aspect. It contains Advice and Pointcut. public aspect MyAspect { //Following line is Pointcut: Following piece of advice will run BEFORE execution of testAspectj() method of ANY class. before():execution(* *.testAspectj()) { //Next line is Advice. A piece of code that will be executed at certain pointcuts. System.out.println("Before execution of testAspectj() method"); } } -- -- -- Without Aspectj, running the application will yield output: > Testing Aspectj With Aspectj enabled, running the application will yield output: > Before execution of testAspectj() method > Testing Aspectj
Notes:
- AOP is concept/paradigm. Aspectj is its implementation.
- Need of good logging: Logging is an important component of the software development. A well-written logging code offers quick debugging, easy maintenance, and structured storage of an application’s runtime information.
Video for NetBeans Installation: https://www.youtube.com/watch?v=DgF_5bRH9-Q
References:
Good but a tad complex starting point: http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html
Intro on AOP with Aspectj explaining why and where it can be used: http://www.christianschenk.org/blog/aop-with-aspectj/
Cross cutting example: http://stackoverflow.com/questions/23700540/cross-cutting-concern-example
Official Aspectj guide: https://eclipse.org/aspectj/doc/next/progguide
AOP in real life: http://makble.com/aop-in-real-world-examples
Brief and to the point explanation: http://www.javatpoint.com/spring-aop-tutorial
Leave a Reply