13

I am working with Spring 3.0 framework and still a novice. Can anyone explain me in layman terms what is AOP programming? (a short example will definitely help)

How does Spring incorporate/enhance/support it?

Premraj
  • 72,055
  • 26
  • 237
  • 180
aces.
  • 3,902
  • 10
  • 38
  • 48
  • Take a look at [Spring's manuals](http://static.springsource.org/spring/docs/3.0.x/reference/aop.html), they truly are really awesome (honest!) – Mark Elliot Apr 08 '11 at 01:03
  • 1
    I have tried to read up articles, manuals and forums to understand AOP, however I get confounded with all the vague terms and abstract language used(my tiny brain shuts down trying to process the terms) – aces. Apr 08 '11 at 01:08
  • 1
    Spring in Action, Third Edition at http://www.manning.com/walls4/ gives an excellent explanation of Aspect Oriented Programming with Spring. – Derek Mahar Apr 08 '11 at 03:13
  • I would suggest you follow this tutorial from theory to code examples: [Understanding Spring AOP](http://www.codejava.net/frameworks/spring/understanding-spring-aop) – Nam Dec 22 '12 at 14:39
  • Check this article: http://marcin-chwedczuk.github.io/overview-of-spring-annotation-driven-aop – csharpfolk Dec 04 '16 at 10:41

5 Answers5

31

AOP is a way to modify existing classes in a code base to embellish them or change their behavior based on rules defined separately. This modification can be done before the classes are put into a jar/war, or can happen dynamically while the code is being loaded.

The idea is, rather than finding all the points of code that you want to modify in the source code and hand modifying them, you define rules for how to find points of interest in the code base, and what embellishments you would like to do to them. These rules are called aspects (the A of AOP).

The prototypical example is you want to get some timing information on various methods in your code base. You could go find all the methods of interest and at the top put a call to

long start = System.currentTimeMillis();

and at the end do

long end = System.currentTimeMillis();
System.out.println("Method time is: " + (end - start));

but that is:

  1. probably a bunch of work
  2. temporary, and you don't want to muck up your code base

You can instead define aspects that say what methods you want to modify, and that you want to do stuff at the beginning and end of these methods.

When the AOP is applied, either at jar creation time, or class loading time, it's as if you wrote the classes that way originally.

Piotrek Hryciuk
  • 785
  • 10
  • 23
MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66
  • 1
    This was surely helpful.Can you provide any helpful links/articles which are very useful and easy for beginners ,like me, to understand? – aces. Apr 08 '11 at 01:15
  • 3
    Unfortunately, it seems that those who develop/evangelize AOP tend to think of it as a higher level of abstraction than regular programming, and so present the material in a relatively high-brow way, full of new terminology and overly complicating rhetoric. I looked around for samples, and this one is as close to a 'just do this' kind of exercise that I can find. It's probably easier to understand than most: http://www.andrewewhite.net/wordpress/2010/03/17/aspectj-annotation-tutorial/ It's by no means anywhere near complete, but might get you a taste. – MeBigFatGuy Apr 08 '11 at 05:08
7

Aspect Oriented Programming is sensibly new and it is not a replacement for Object Oriented Programming. In fact, AOP is another way of organizing your Program Structure.

To be more clear I will use some diagrams:

  1. What is Aspect?

    |---------------------|------------------|------------------|
    |      Aspect         =     Point cut    +  Advice          |
    |---------------------|------------------|------------------|
    |                     | Where the aspect | What code is     |
    |                     |  is applied      |  executed.       |
    |---------------------|------------------|------------------|
    

    Aspect = Point cut + Advice

  2. Type of Advice methods

    enter image description here

  3. Aspect Example

    @Around( "execution(* *(..))" )
    public Object trace(ProceedingJoinPointproceedingJP)throwsThrowable{
        String methodInformation= proceedingJP.getStaticPart().getSignature().toString();
        logger.trace("Entering "+methodInformation);
        try{
            returnproceedingJP.proceed();
        } catch(Throwable ex) {
            logger.error("Exception in "+methodInformation, ex);
            throw ex;
        } finally {
             logger.trace("Exiting "+methodInformation);
        }
    }
    
leiyc
  • 903
  • 11
  • 23
Xelian
  • 16,680
  • 25
  • 99
  • 152
7

AOP is a pattern used to modularize cross cutting features. So if there is a certain "thing" that applies to a significant part in your code then you can use AOP to solve that problem. These "things" are called aspects.

An example below:

An exception logger is used across the enterprise app. So you could set it up using AOP the following way. So now all methods under my.service package will get logged the following way.

  <bean id="exceptionLogger" class="my.good.ExceptionLogger" />  
        <aop:config>
                <aop:pointcut id="allServiceMethods" expression="execution(* my.service.*(..))" />
                <aop:aspect id="serviceLogger" ref="exceptionLogger">
                    <aop:after-throwing pointcut-ref="allServiceMethods"
                                        method="logIt"
                                        throwing="e"/>
                </aop:aspect>  
        </aop:config>

And the ExceptionLogger class could be something like below:-

public class ExceptionLogger {
    private static Logger logger = Logger.getLogger(ExceptionLogger.class);
    public void logIt(JoinPoint jp, Exception e) {
        StringBuilder msg = new StringBuilder();
        msg.append("<whatever makes sense>");
        logger.error(msg.toString());
    }
}

Also take a look at this relevant question:-

  1. What is the most common use for AOP in spring project
Community
  • 1
  • 1
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
  • 1
    'AOP is a pattern used to modularize cross cutting features.' Can you explain this statement? what do you mean by cross-cutting features? Can you provide any helpful links/articles to explain this? Thanks – aces. Apr 08 '11 at 01:14
  • 1
    Logging, transaction management, timing (as @MeBigFatGuy) mentioned in his post are good examples of cross cutting. Since these in general applies to all methods. Therefore instead of writing the same boiler plate code over and over again, you define them as aspects and voila spring does its magic or you. Hope this helps! – CoolBeans Apr 08 '11 at 01:16
6

AOP enables cohesive development by separation(module) of Cross Cutting Concerns into Aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

For example: Logging, Transaction and security are some Aspects. In Logging we may have different aspect i.e. time calculation logging, simple in and out message logging and so on..

  • Advise defines what needs to be apply.
  • Joinpoint is where an Advice is apply.
  • Pointcut is a combination of different Jointpoints.
  • Aspect is applying an Advice at Pointcuts.

Note: Spring does not support AOP for methods marked as final.

enter image description here

Source


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

Source


Spring provides declarative programming with AOP. This is a better way to implement cross cutting concerns without the needs to use plumbing code all over the core business classes. AOP enables you to think about concerns or aspects in your system. Typical concerns are transaction management, logging etc. AOP enables you to capture the cross-cutting code in modules such as interceptors that can be applied declaratively wherever the concern they express applies. Spring includes a proxy-based AOP framework.

Source

Premraj
  • 72,055
  • 26
  • 237
  • 180
1

In a nutshell, AOP is a mathematician's way of explaining how you should organize your code neatly to avoid having a particular functionality scattered in bits and pieces across lots of modules or object. At its heart, AOP is a good thing whether or not it is called AOP.

But you are faced with a specific AOP implementation and need to figure out how to use it. I think the best way to do this is to look for blogs where people post recipes and examples of how they are using it with Spring. This way you bypass the mathemeticians and get to read the writings of engineers who are more in touch with reality.

There are two kinds of computer scientists, mathematicians who delight in the obscure and use tortured terminology to explain simple things, and engineers who will tell you step by step how to build software. Working programmers tend to be more of the engineer mindset because abstract thinkers find it hard to handle the long slog of gaining experience. That's why you find AOP hard to understand. Not because it is hard to understand, but because it is explained so poorly by abstract mathematical thinkers who are not terribly familiar with "plain English".

I wonder what would happen if an AOP guru sat down with a Function Point Analysis guru.

Michael Dillon
  • 31,973
  • 6
  • 70
  • 106