Spring AOP (Aspect Oriented Programming)  breaks the program logic into distinct parts (called concerns). It is used to increase modularity by cross-cutting concerns.

A cross-cutting concern includes concerns such as transaction management,logging,security etc. AOP provides the pluggable way to dynamically add the additional concern before, after or around the actual logic. Suppose there are 5 methods in a class and we need to log some statements inside all methods.

Before AOP : we need to write the logging code inside each method. Now suppose the client comes and says he doesn’t want the logging code. So again you need to change the code which is troublesome. Spring AOP comes to rescue.

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 comes with below important concepts

1.Join point

Join point is any point in your program such as method execution, exception handling, field access etc. Spring supports only method execution join point.

2.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.

3.Pointcut

It is an expression language of AOP that matches join points.

4.Target Object

It is the object i.e. being advised by one or more aspects. It is also known as proxied object in spring because Spring AOP is implemented using runtime proxies.

5.Aspect

It is a class that contains advices, joinpoints etc.

6.AOP Proxy

It is used to implement aspect contracts, created by AOP framework. It will be a JDK dynamic proxy or CGLIB proxy in spring framework.

AOP implemetations can be done by

1.Spring AOP

2.AspectJ

3.Jboss AOP

We will show you the Spring AOP AspectJ annotation example here:

College.java

ioc

 

Aspect class:

ioc

 

As you can see from above, we have an Aspect class which has a pointcut expression which is a set of join points, myAdvice is an advice to which a joinpoint is passed.

Now the pointcut above is such an expression such that the advice is applied on all the methods of class College. Thus System.out.println(“additional concern”); will execute on all the methods of class College before their execution as we have applied a before advice.

This was a sample example to show you what Spring AOP is. Feel free to comment for Spring AOP in comments section.