• Home
  • RSS Feed
  • Log in

The problem with proxy-based AOP frameworks
Posted by Vincent Partington around lunchtime: August 18th, 2006

Proxy-based AOP frameworks like the one in the Spring Framework have a not oft discussed problem. When a method in a class invokes another method in the same class (or a superclass), any interceptors on that second method are not executed. This unexpected behaviour can have serious consequences when the interceptor delivers important services like transactions or security.

Let's say we are implementing an application for a bank where only certain employees are allowed to perform a credit check on suspect transaction, e.g. those exceeding 1 million euros. Using Aspect Oriented Programming this can be implemented as follows:

When processed by AspectJ's precompiler, the following woven class is output:

As you can see in the picture, when the method processPayment is invoked, the correct security check is performed when the checkCreditRating method is invoked.

However, that precompilation step was perceived as complicated and hard to integrate into the build proces (and not every IDE has appropiate plugins). This led to the appearance of proxy-based AOP solutions such as dynaop and Spring's AOP framework. A precompilation step is no longer necessary. Instead, a proxy is created on the fly. This proxy performs the functionality defined in the aspect before (and after) invoking the method in the original object:

Apart from only offering method interception instead of the full range of AOP functionality, this approach has one other, not often discussed, drawback. When invoking the checkCreditRating method on the proxy, the security check is correctly performed. However, when invoking the processPayment method on the proxy (see the picture), control is passed to the processPayment method in the original object which invokes this.checkCreditRating() directly, thereby bypassing the security check. This occurs because this in the original object refers to that object itself instead of the proxy.

Other functionality that assumes the identity of the proxy and the identity of the original object are identical will fail too. As mentioned in GoF on page 178 when discussing the Decorator pattern:

3. A decorator and its component aren't identical. A decorator acts as a transparent enclosure. But from an object identity point of view, a decorated component is not identical to the component itself. Hence you shouldn't rely on object identity when you use decorators.

This is an unexpected result of the proxy-based implementation of AOP and one that you need to be especially aware of when implementing important functionality in a aspect!

  • Share/Bookmark

Filed under AOP, Java, Spring | 8 Comments »



8 Responses to “The problem with proxy-based AOP frameworks”



    Alef Arendsen Says:
    Posted at: August 22, 2006 at 2:27 am

    Hi Vincent,

    yes, provy-based AOP solution do have this specific drawback, although I haven’t seen it become a real bottleneck in any of the projects I’ve encountered. Good to spread the word though, as knowing about it is a good first step.

    Your security use case is one situation where the problem might occur, another is different propagation levels on method within the same class.

    class MyClass {

    // propagation=REQUIRES
    void doIt() {
    this.doIt2();
    }

    // propagation=REQUIRES_NEW
    void doIt2() {
    }
    }

    Note that Load-Time-Weaving (LTW) has solved lots of the deploytime configuration problems that AspectJ used to come with. Using LTW does involve some additional configuration, but you don’t necessarily have to issue a post compilation step anymore. This works nicely together with the new Java 5 agents.

    cheers,
    Alef



    Vincent Partington Says:
    Posted at: August 23, 2006 at 2:15 pm

    Hi Alef,

    I expect a lot from the LTW features of AspectJ 5. Not only will it solve this deficiency of the proxy-based AOP solution, it will also allow developers to use the more exotic AOP features such as introductions.

    Regards, Vincent.



    Erwin Bolwidt Says:
    Posted at: August 23, 2006 at 5:39 pm

    Hi Vincent & Alef,

    In applications where one comes across this issue occasionally, and one is not ready to use LTW, one can use the AopContext solution.

    On any ProxyFactoryBean you can set the ‘exposeProxy’ property to ‘true’ (it is false by default, for performance reasons, but the performance impact is very small.)

    This property cooperates with the class org.springframework.aop.framework.AopContext, in such a way that it makes the AOP proxy available to the proxied instance.

    Sounds complicated?

    An example:

    Say your BankService’s processPayment method needs to call checkCreditRating, but needs all security inerceptors to be invoked.

    Instead of calling this.checkCreditRating(), it calls

    BankService proxy = (BankService) AopContext.getCurrentProxy();
    proxy.checkCreditRating();

    It won’t receive any awards for beautiful code, but if not too frequently used, it is a good workaround.

    I’ve used it in practice with one addition: to make unit testing easier; adding a fallback to an injectable property in the case that AopContext didn’t return a value. (Which occurs when running the code without an interceptor, in a unit test)

    Regards,
    Erwin



    Alex Popescu Says:
    Posted at: September 16, 2006 at 1:30 am

    The entry is quite interesting, but it needs a small correction: AspectWerkz is/was not a proxy-based AOP solution. It offered an additional functionality to work with proxies, but the core was a weaving based AOP solution (it performed the weaving with the help of classloaders).

    ./alex
    –
    .w( the_mindstorm )p.
    AspectWerkz developer



    Vincent Partington Says:
    Posted at: September 20, 2006 at 11:51 am

    Oops. my bad, Alex. I’ve fixed the article.

    Regards, Vincent.



    Patrick Vanbrabant Says:
    Posted at: October 4, 2006 at 1:16 am

    Erwin,

    Regarding the AopContext solution, I think this is not a real solution anyway.

    In this case the class itself must know that there is an advise applied to some of its methods. In the case of the BankAccount this may seam trivial, but lets look at an even more down to earth example.

    The textbook case for applying Aop would be logging or monitoring. Lets assume that we have a simple logging advice that we want to apply on each method of the interface.

    Then the developer of each class must know whether this class will always have the advide applied to it. Sounds a little like mixing of concerns.

    If we then want to turn of (and on again) the logging in a production environment we have to change all the code again. Like I saym not a real solution.

    Just my five cents.

    KR

    Patrick



    Java Competence Centre LogicaCMG » Having fun with Spring AOP II Says:
    Posted at: October 23, 2006 at 9:13 pm

    [...] After my initial explorations of the AspectJ-support offered by Spring, someone (actually, I think it was google again) pointed me to this article about the drawbacks of proxied aop. A good read written by Vincent Partington that shows the internals of  how and why a proxy based aop framework can ignore your carefully injected aspects. A ‘must-be-aware-of’ for every Spring 2.0 user! [...]



    Vincent Partington Says:
    Posted at: October 28, 2006 at 10:46 am

    Hi Okke from LogicaCMG,

    (Note: I tried replying to your blog but my remark did not appear there)

    Nice idea to use AOP to address a problem in AOP. :)

    Two remarks though:
    - AspectJ is _not_ a proxy-based AOP solution so you would not have the problem there. It’s only when using Spring 1.x’s proxy-based AOP stuff that you’d have to aware of the problem I described.
    - You can use inter-type declarations to introduce the member “proxy” in all @Proxied classes. See
    http://www.eclipse.org/aspectj/doc/released/progguide/starting-aspectj.html#inter-type-declarations

    Regards, Vincent.



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    Agile Awareness Workshop Grails IntelliJ Groovy esb fitnesse Introduction to Agile Semantic Web Scala Spring product owner XML Closures Poppendieck Java Testing Performance JavaOne Architecture Xebia Functional Programming qcon Scrum Maven Lean Seam SOA Agile Ajax Hibernate
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs