Aspect Oriented Programming (AOP) and Spring

AOP is all about adding aspects to your code. So what are aspects? The code that we apply on Cross Cutting Concerns. Then what is Cross Cutting Concerns? Aspect, Jointpoint, Pointcut, Cross Cutting Concerns, Advice etc are the frequently used word in AOP world. AOP decomposes a system into concerns, instead of objects.

 

Aspect: It’s like a general feature you want to apply globally to your application like logging, exception handling, transaction management, performance management etc. It is also called Cross Cutting Concerns.

Advice: It is a piece of code/logic for implementing your advice.

Joinpoint: A single location in the program where an advice is applied like method invocation, constructor invocation etc.

Pointcut: A pointcut is set of Joinpoint where an advice is applied. In Spring set of method invocation is called Pointcut. There are different types of pointcut in spring like Regular Expression Pointcut, Attribute Driven Pointcut, and Dynamic Pointcut etc

Targets/Target Objects: The objects you want to apply an aspect or set of aspects.

As per me advice is very similar to Decorator. You can implement an advice by implementing org.aopalliance.intercept.MethodIntercept interface of spring. The MethodInterceptor interface is actually a child of the org.aopalliance.intercept.Interceptor interface, which is a child of another interface org.aopalliance.aop.Advice. In spring we generally use method interceptor. That is designed for method-invocation style advice. The MethodIntercept is really simple

 

public interface MethodInterceptor extends Interceptor {

            Object invoke(MethodInvocation invocation) throws Throwable;

}

Basically, when you write an advice for intercepting a method, you have to implement one method - the invoke method, and you are given a MethodInvocation object to work with. The MethodInvocation object tells us a bunch of stuff about the method that we’re intercepting, and also gives a hook to tell the method to go ahead and run.

public class LoginInterceptor implements MethodInterceptor {

           public Object invoke(MethodInvocation methodInvocation) throws Throwable {

               Log logger = LogFactory.getLog(methodInvocation.getClass());

               long startTime = System.currentTimeMillis();

               try {

                               Object[] args = methodInvocation.getArguments();

                               if (logger.isDebugEnabled()) {

                                    logger.debug(”Beginning method: ” +

                                                             methodInvocation.getMethod().getDeclaringClass() + “::” +

                                                             methodInvocation.getMethod().getName());

                                   if (null != args) {

                                               logger.debug(” with arguments: ” + args.toString());

                                   } else {

                                              logger.debug(” with no arguments”);

                                   }

 

                                    logger.debug(System.getProperty(”line.separator”));

                               } else if (logger.isInfoEnabled()) {

                                        logger.info(”Beginning method: ” + methodInvocation.getMethod().getDeclaringClass()

                                              + “::” + methodInvocation.getMethod().getName());

                                      logger.info(System.getProperty(”line.separator”));

                               }

                                              Object retVal = methodInvocation.proceed();

                               return retVal;

                      } finally {

                               if (logger.isInfoEnabled()) {

                               logger.info(”Ending method: ” +  methodInvocation.getMethod().getDeclaringClass() + “::” +

                               methodInvocation.getMethod().getName());

                               logger.info(”Method invocation time: ” + (System.currentTimeMillis() - startTime) + ”

                               msecs.”);

                               logger.info(System.getProperty(”line.separator”));

                                   }

                    }

           }

}

XML configuration for above interceptor is given below:

 

<bean id=”studentServiceTarget” class=”com.example.StudentServiceImpl”/>

 

<bean id=”myLogger” class=”com.example.LoginInterceptor”/>

   

<bean id=”studentService”

    class=”org.springframework.aop.framework.ProxyFactoryBean”>

    <property name=”proxyInterfaces”><value>com.example.StudentService</value></property>

    <property name=”target”><ref local=”studentServiceTarget”/></property>

    <property name=”interceptorNames”>

        <list>

            <value>myAdvisorLogger</value>

         </list>

    </property>

</bean>

 

Spring has multiple alternatives to the basic MethodInterceptor , however, (which is referred to in the Spring documentation as an ‘around’ advice) so that if you want to do more specific things, you can with less complication - these extensions come in the form of Spring-specific extensions to the Advice interface (siblings to the MethodInterceptor interface), and they include:

·         org.springframework.aop.MethodBeforeAdvice - Implementations of this interface have to implement this before method:

void before(Method method, Object[] args, Object target) throws Throwable;

·         org.springframework.aop.AfterReturningAdvice - This interface’s method will be called on the return from the invocation of a method. Implementation of this interface have to implement this afterReturning method:

            void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable;

·         org.springframework.aop.ThrowsAdvice – Implementation of this interface havt to implement this afterThrowing method:

            void afterThrowing([Method], [args], [target], [some type of throwable] subclass)

 Below are hierarchy of Advice class:

 

In above article I have given only basic information about AOP. 

 

Reference Material:

·         http://static.springframework.org/spring/docs/1.2.x/reference/aop.html.

·        Spring in Action by Craig Walls, Ryan Breidenbach: this is the best book I have read on Spring (and yes I read this entire book).

Leave a comment

Your comment

  • malte roger engagement
  • dons and bens
  • curtin ethical framework
  • name mathias kraft
  • richard snowden esq
  • muncie indaina dermatologist
  • defenition of creative arts
  • pouches
  • eileen
  • arts fest solomons md
  • certificates
  • high gloss rocks
  • downing
  • silvana dix
  • conclusa designed by phpbb
  • antonym of gawk
  • taurus 1911 malfunction magazine
  • performance boxer briefs
  • fudge
  • chips
  • msds for ammonium phosphate
  • gwendoline cram old perlican
  • displacement
  • weymouth yesterday temperature
  • malaga island maine
  • breitling chrono avenger prices
  • multinational companies in trinidad
  • robert l foote thyroid
  • traveler hook
  • tudra biome advantages
  • strategies
  • pictures of pecans walnuts
  • un segundo de paz
  • oregon solicitation laws
  • pharos science gps
  • ixtapa bayview grand rentals
  • used fire apparatus sales
  • 135 ludlow northvale
  • covering letters freee stuff
  • lisa marie pressley tmz
  • natural foods jessup maryland
  • answers please
  • latest hilary duff song
  • 2000 alero remote
  • ethel wicke iowa
  • abrahams lincolns life
  • matches
  • national wireing color code
  • hombres usan aretes
  • pennslyvania cencus
  • pyramid
  • ssis runtime oledb connection
  • johnstown
  • chicco canada
  • tube by elias chatzoudis
  • barra macneils the
  • hedwig k nig
  • ged waynesville missouri
  • top eyewear in seattle
  • hunting hounds for sale
  • bursitis spelling
  • maidstone hospital address
  • flexibility for dancers
  • sanjuanita cardenas sentence
  • using hard anodized cookware
  • trybuilt chipper shreder
  • suture technique
  • baja fresh franchises information
  • mc kinney texas hospital
  • dentzel carousel horse history
  • ukraine
  • quintana roo rehab centers
  • sybil identity revealed
  • bestar granite graphite 4500
  • hypothalamus and cortisol
  • kauai
  • mitzi lafarga
  • human resouces jobs
  • sophia loren soldi
  • boon wah hotel
  • cherish the child
  • purgatory chasms
  • restrictions on proprietary code
  • higgins
  • tom calhoun portland
  • novel by marilyn halverson
  • teen storie about dating
  • livin gluten free
  • wd boyce council bsa
  • wendys closing
  • saber motorcycle helmets
  • senor ferrari 1942 casablanca
  • daddys poem
  • aprendizaje conductista
  • dilution
  • kalle anka video
  • couplers
  • golden gophers apparel
  • navi honda hacks
  • benoit northeast hunter magazine
  • saidi bellydance costume
  • vrbo around yellowstone no
  • r b musc listing
  • el campo inn
  • towler shaw roberts wolverhampton
  • audobon society central florida
  • baghdad
  • utility locating software
  • readily available biographical information
  • entrance
  • ryland homes fargo
  • tanja schmitz
  • through the pouring rain
  • bases plural of basis
  • lifespan development flash cards
  • crazy
  • scott monahan motorcycle
  • classic cajun rialto california
  • armani exhange uk shops
  • fairfield illinois broadband internet
  • gravity fed racks
  • glaser
  • clair
  • 25th infantry division coin
  • panda express restruant
  • docking windows
  • connected vehicle proving center
  • romana guenzi
  • malcolm robb west australia
  • lifecycle of blowfly
  • robert theodore stafford said
  • quantas brisbane airport
  • knitting argyl vest pattern
  • english pubs in seattle
  • dislocated shoulder complictions
  • century 21 chillicothe mo
  • nukem die for
  • beauport guadeloupe population
  • recovery mobility formula
  • fusion sabot slugs
  • coiled solar panels
  • interchangeable
  • stronghold 2 data
  • bombs over bagdah
  • best cucumber sandwich
  • tonya lacy model
  • street addresses from ips
  • elastic goods
  • cold chocolate souffle recipes
  • disconnect
  • sejarah lari sambung
  • marine fishes wallpaper
  • hope diamond located where
  • burgers
  • zino sumatra classic
  • gastonia apartment finder
  • 1885
  • sort
  • thomson mp231 players
  • hotspots in eindhoven
  • pesticide regulation product chemistry
  • gates
  • jame
  • texas meatloaf recipe
  • cherokee
  • stairway
  • teaching elementary classroom management
  • betty coker price
  • boyfriend
  • avengers heroes reborn
  • genuine flan recipes
  • veronica da souza pics
  • slippers for toddlers
  • kolb cycle of learning
  • vina herminia excelsus
  • belmont
  • art as symbolic form
  • spca in coquitlam
  • internal
  • bavarian summer festival
  • jorge hank rodolfo valdes
  • life expectancy green algae
  • lillie allen smile
  • castle marne inn denver
  • wimax hotspots in lisbon
  • mathew reilly novels
  • compatibility mode for itunes
  • haller foundation
  • scripps ranch contact lenses
  • miguel cotto interview
  • penrose brain quantum
  • hydrocarbon products
  • dram manufacturing explained
  • rich homeless people
  • onngaleah s huff realty
  • connor
  • hariet tubman for kids
  • knife sharpening systems