Spring AOP

One of the key components of Spring Framework is the Aspect oriented programming (AOP) framework. Aspect-Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic. There are various common good examples of aspects like logging, auditing, declarative transactions, security, caching, etc.

The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency Injection helps you decouple your application objects from each other and AOP helps you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in programming languages such as Perl, .NET, Java, and others.

Spring AOP module provides interceptors to intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution.


AOP Terminologies

Before we start working with AOP, let us become familiar with the AOP concepts and terminology. These terms are not specific to Spring, rather they are related to AOP.

  • Aspect:This is a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement.
  • Join point:This represents a point in your application where you can plug-in the AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.
  • Advice:This is the actual action to be taken either before or after the method execution. This is an actual piece of code that is invoked during the program execution by Spring AOP framework.
    • before : Run advice before the a method execution.
    • after: Run advice after the method execution, regardless of its outcome.
    • after-returning: Run advice after the a method execution only if method completes successfully.
    • after-throwing: Run advice after the a method execution only if method exits by throwing an exception.
    • around:Run advice before and after the advised method is invoked.
  • Pointcut:This is a set of one or more join points where an advice should be executed. You can specify pointcuts using expressions or patterns.
  • Introduction:An introduction allows you to add new methods or attributes to the existing classes.
  • Target object:The object being advised by one or more aspects. This object will always be a proxied object, also referred to as the advised object.
  • Weaving:Weaving is the process of linking aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime.


Types of Advice

  • before : Run advice before the a method execution.
  • after: Run advice after the method execution, regardless of its outcome.
  • after-returning: Run advice after the a method execution only if method completes successfully.
  • after-throwing: Run advice after the a method execution only if method exits by throwing an exception.
  • around:Run advice before and after the advised method is invoked.

Custom Aspects Implementation

Spring supports the @AspectJ annotation style approach and the schema-based approach to implement custom aspects. These two approaches have been explained in detail in the following sections.

Spring AOP Interview Questions

What is Spring AOP? What is its use

Suppose we want to log every method entry and exit. This can be achieved by writing log statements in every method at the start and end. But this will require lot of code work. There are various such tasks like Security which need to be applied across all methods or classes. These are known as cross cutting concerns. AOP addresses the problem of cross-cutting concerns, which would be any kind of code that is repeated in different methods and cannot normally be completely refactored into its own module, like with logging or verification.

What Are The Limitations Of Spring Aop?

  • Can only advise non-private methods
  • Can only apply aspects to Spring Beans
  • Limitations of weaving with proxies
  • When using proxies, suppose method a() calls method b() on the same class/interface
  • advice will never be executed for method b()

What Are The Supported Aspectj Pointcut Designators In Spring Aop?

  • Execution
  • This
  • Target
  • Args
  • @target
  • @args
  • @within
  • @annotation

How To Declare Aspect In Spring Aop?

In XML:

<bean class="com.doj.aop.LoggingAspect" id="loggingAspect">
     <!-- configure properties of aspect here -->
</bean>

In Java:

@Aspect
@Component
class LoggingAspect{
   //advice
   //pointcut 
}


How To Declare A Pointcut In Spring Aop?

@Pointcut("execution(* save(..))")
private void dataSave {}



What are the different implementations of Spring AOP ?

The different implementations of Spring AOP are-

  • AspectJ
  • Spring AOP
  • JBoss AOP

Define Run-time AOP vs Compile-time AOP ?

The different types of AOPs depending on when they are loaded are-

  • Source code weaving: Aspect code is injected as source code statements into your application source code. This is some kind of preprocessor approach. No AOP framework in the Java world uses this approach nowadays, but there used to be some in the early days of AOP.
  • Compile-time weaving: Aspect code is woven into your application by a special compiler.
  • Binary weaving: Aspect code is woven into existing class files after compilation rather than during compilation.
  • Load-time weaving (LTW): A weaving agent/library is loaded early when your VM/container is started. It gets a configuration file with rules describing which aspects should be woven into which classes.
  • Proxy-based LTW: This special LTW form is used by Spring AOP while AspectJ does the previous 3 forms listed above. It works by creating dynamic proxies (i.e. subclasses or interface implementations) for aspect targets.

How Does Spring Solve (implement) A Cross Cutting Concern?

Implement your mainline application logic:

  • Focusing on the core problem
  • Write aspects to implement your cross-cutting concerns
  • Spring provides many aspects out-of-the-box Weave the aspects into your application
  • Adding the cross-cutting behaviors to the right places.

Which Are The Limitations Of The Two Proxy-types?

Spring will create either JDK or CGLib proxies

  • JDK Proxy
    • Also called dynamic proxies
    • API is built into the JDK
    • Requirements: Java interface(s)
    • All interfaces proxied
  • CGLib Proxy
    • NOT built into JDK
    • Included in Spring jars
    • Used when interface not available
    • Cannot be applied to final classes or method

Name Three Typical Cross Cutting Concerns?

    • Logging
    • Security
    • Transaction

What Is A Named Pointcut?

A named pointcut can be declared inside an <aop:config> element, enabling the pointcut definition to be shared across several aspects and advisors.

<aop:config>
    <aop:pointcut id="businessService" expression="execution(* com.xyz.myapp.service.*.*(..))"/>
</aop:config>

How Do You Externalize Pointcuts? What Is The Advantage Of Doing This?

Externalize the pointcut to a named pointcut. Avoid to writing complex pointcut expression across the application.

What Is The Joinpoint Argument Used For?

Context provided by the JoinPoint parameter and Context about the intercepted point.

What Is A Proceedingjoinpoint?

An around advice is a special advice that can control when and if a method (or other join point) is executed. This is true for around advices only, so they require an argument of type ProceedingJoinPoint, whereas other advices just use a plain JoinPoint. ProceedingJoinPoint is used as an argument of the methods which hints for before, after, after throwing and around. ProceedingJoinPoint has the methods like getKind, getTarget, proceed etc.

What Do You Understand By Load-time Weaving (ltw) In Spring?

Load-time weaving (LTW) or Run time weaving is a process of weaving AspectJ aspects into the classes of the application when the classes are being loaded in JVM.

What Is Aspect Oriented Programming (aop) In Spring?

Aspect Oriented Programming works like Object Oriented Programming. In Object Oriented Programming, the unit of modularity is Object But in Aspect Oriented Programming the unit of modularity is Aspect. Aspect works as the modularization of concerns known as crosscutting concerns in AOP. AOP framework is pluggable in spring. AOP provides declarative enterprise service and allows users to implement custom aspects.


How To Enable @aspectj Support?

Include the below XML code in application XML

<aop:aspectj-autoproxy/>

When To Use Spring Aop And When To Use Full Aspectj?

If we only need to advice the execution of operations on Spring beans then we should use Spring AOP. Spring AOP is simpler than AspectJ. Full AspectJ requires the AspectJ complier in the build process.

In case if we advice objects not to be managed by Spring Container, use AspectJ.

What Is The Concept Of Aop? Which Problem Does It Solve?

Aspect-Oriented Programming (AOP) is another way of thing to some areas of application i.e. cross cutting concern like security, logging and transaction. AOP is simple complement of OOP programming for different concerns. In OOP, the key unit of modularity is the class, whereas in AOP the unit of modularity is the aspect.

Aspect-Oriented Programming (AOP) enables modularization of cross-cutting concerns to solve following problems.

  • To avoid tangling
  • To eliminate scattering.