An Introduction to Aspect-Oriented programming with JBoss AOP

Observer with Introductions and Mixins

Say we want to be able to be notified somehow when BankAccount.balance is changed. An option would be to implement the Observer pattern, but we don't want to include all the Observable plumbing code in our BankAccount class. First of all let's add an annotation to the field we want to monitor.

package bank;

public class BankAccount
{
int accountNumber;

@Observed
int balance;
...
}

 

Next we can write an implementation of Observable:

package bank;

import java.util.ArrayList;
import java.util.List;

public class ObservableMixin implements Observable
{
List<Observer> observers = new ArrayList<Observer>();

public void addObserver(Observer listener)
{
observers.add(listener);
}

public void removeObserver(Observer listener)
{
observers.remove(listener);
}

public void notifyObservers(Object event)
{
for (Observer observer : observers)
{
observer.update(event);
}
}
}

 

This is a mixin class, which implements the Observable interface. It contains all the plumbing code needed for the Observable part of the pattern. It can be introduced into other POJOs using the following xml

<aop>
<introduction expr="hasfield(* *->@bank.Observed)">
<mixin>
<interfaces>
bank.Observable
</interfaces>
<class>bank.ObservableMixin</class>
</mixin>
</introduction>
...


This does two things. It makes all classes that have a field annotated with @Observed implement the @Observable interface and implement those methods. Second, when anybody attempts to call the methods from the Observable interface, it delegates all the calls to an instance of the ObservableMixin.

Next we have an aspect to trap when the annotated fields change their values bound using the following xml.

...
<aspect class="bank.ObserverAspect"/>

<bind pointcut="set(* bank.BankAccount->@bank.Observed)">
<around aspect="bank.ObserverAspect" name="fieldChanged"/>
</bind>
</aop>

 

The aspect is an around advice that captures the values before and after modifying the field.

package bank;

import java.lang.reflect.Field;

import org.jboss.aop.joinpoint.FieldWriteInvocation;

public class ObserverAspect
{
public Object fieldChanged(FieldWriteInvocation invocation) throws Throwable
{
Observable tgt = (Observable)invocation.getTargetObject();
Field fld = invocation.getField();
String fieldName = fld.getName();
fld.setAccessible(true);
Object oldVal = invocation.getField().get(tgt);
Object result = invocation.invokeNext();
Object newVal = invocation.getField().get(tgt);

tgt.notifyObservers("Changed " + fieldName + " from " + oldVal + " to " + newVal);

return result;
}
}


Since the classes captured by the pointcut to select which classes should have the ObserverAspect applied are in the set of classes captured by the class expression to pick out classes that should have the Observable introduction and mixin, we can safely cast the target of the invocation to Observable. We then get the values before and after writing the field, and then use the Observable target object to notify the observers. As mentioned the call to Observable.notifyObservers() will end up inside BankAccount's ObservableMixin.

Finally, let us modify the Bank.main() method to register an Observer with a BankAccount instance

public static void main(String[] args)
{
System.out.println("*** Creating account 1");
BankAccount acc1 = new BankAccount(1);
acc1.credit(150);
bankAccounts.put(acc1.getAccountNumber(), acc1);

System.out.println("*** Creating account 2");
BankAccount acc2 = new BankAccount(2);
acc2.credit(230);
bankAccounts.put(acc2.getAccountNumber(), acc2);

System.out.println("Installing observer");
((Observable)acc2).addObserver(new Observer(){
public void update(Object evt)
{
System.out.println("!!! Observer: " + evt);
}

});

System.out.println("*** Balance acount 1: " + acc1.getBalance());
System.out.println("*** Balance acount 2: " + acc2.getBalance());

//Transfer some money
System.out.println("*** Transfer 50 from account 1 to account 2");
transfer(acc1, acc2, 50);

System.out.println("*** Balance acount 1: " + acc1.getBalance());
System.out.println("*** Balance acount 2: " + acc2.getBalance());
}

 

Although until woven the BankAccount class does not implement the Observable interface, the Java compiler does not perform any checks when casting to an interface (only to a superclass), so the cast from BankAccount to Observable will compile. (If the example is run without weaving you would get a ClassCastException since then BankAccount would not implement the Observable interface). When we run this example we can see the registered Observer gets triggered:

*** Creating account 1
*** Bank Account constructor
*** BankAccount.credit()
*** Creating account 2
*** Bank Account constructor
*** BankAccount.credit()
Installing observer
*** Balance acount 1: 150
*** Balance acount 2: 230
*** Transfer 50 from account 1 to account 2
*** BankAccount.debit()
*** BankAccount.credit()
!!! Observer: Changed balance from 230 to 280
*** Balance acount 1: 100
*** Balance acount 2: 280



The code for this example can be found in the listing5/ folder of the download bundle.

Conclusion

We have taken a simple application, added extra behaviour to it using JBoss AOP, and explored a few of the features offered. Apart from adding a few annotations to help with our pointcut expressions (and there are even less intrusive, although more incovenient ways to achieve the similar effect), we have left the core application as is, and added extra cross-cutting behaviour such as logging and security by applying aspects, as well as using a combination of aspects, interface introductions and mixins to implement the Observer pattern.

JBoss AOP can be downloaded from http://www.jboss.org/jbossaop/ and comes with a tutorial to get you started.

 

AttachmentSize
jboss-aop-samples.zip4.76 MB
0
Average: 3.6 (5 votes)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Joshua Partogi replied on Fri, 2008/08/29 - 10:05pm

This is certainly nice, but can JBoss AOP configured via annotation instead of xml?

jaikiran replied on Sat, 2008/08/30 - 3:52am

Good article, Kabir.

I have a question. Is the aspect code allowed to change the value that is being passed to the  joinpoint? I mean, if the credi(int amount) method was being passed a value of 200, can the code in the aspect change this value to 100 before the credit method is invoked? If yes, is there any way to secure such access?

 

 

Kabir Khan replied on Mon, 2008/09/01 - 5:06am

Joshua,

Yes annotations can be used instead.An example can be found here and the containing directory contains more examples. If using annotations, instead of passing in the path of a jboss-aop.xml file with -Djboss.aop.path, you point JBoss AOP to a directory containing your annotated aspects using -Djboss.aop.class.path. The tutorial examples that come with the download will show how in more detail.

Kabir Khan replied on Mon, 2008/09/01 - 5:13am

Jaikiran,

The aspect code can modify the values that are passed in. There is currently no way to stop this, if that is what you mean by securing it. If this feature is important to you please ask for it on our user forums, and we will take it into consideration. 

gsowji replied on Tue, 2009/02/10 - 11:37pm

I was unable to get the code from this(jboss-aop-samples.zip).

gsowji replied on Wed, 2009/02/11 - 1:18am

can any one of you please update the code samples.

daveeeed replied on Fri, 2009/06/05 - 2:54am

Java is a great platform to work with , I did like its features. It is vast tlike ocean but provides better security than any other. I did like microsoft but java is my favourite. Regards, Insurance Quotes

warrenty replied on Mon, 2009/06/08 - 1:40am

The java and its developers are always rememberd for their great job and the work they did created a great revolution in the history of computers. Regards, Custom Essay

modthoa replied on Wed, 2009/06/17 - 10:51am

Java is a great platform to work with , I did like its features. It is vast tlike ocean but provides better security than any other. I did like microsoft but java is my favourite. Regards, psp games download

emad964 replied on Mon, 2009/06/29 - 4:14pm

تحميل برامج برامج جوالات العاب بنات برامج تكنولوجيا كتب تعليم UltraSurf العاب برامج نت Internet Download Manager ProgDVB برامج مجانية أفضل المواقع العربية دليل مواقع مشاهدة محطات مشفرة Online TV Player 3.0.0.940 Internet Download Manager 5.17 Build 4 رقص شرقي anyTV Pro 4.32 OnLineLive 7.1.1 هزي يانواعم ProgDVB 6.06.2 SopCast 3.0.3 منتدى برامج نت Falco Image Studio 3.6 لعبة تزلج على الجليد UltraSurf 9.4 كاثرين هيغل Katherine Heigl محطة غنوة FreeZ Online TV 1.0 Free Video to Mp3 Converter 3.1.3.51 Advanced MP3 Converter 2.10 Xilisoft Video to Audio Converter 5.1.23.0515 Blaze Media Pro 8.02 AKRAM Media Creator 1.11 DVD Audio Extractor 4.5.4 Free WMA to MP3 Converter 1.16 لعبة نينجا المتقدم لعبة قذف كرة لعبة دراجات البهلوانية لعبة اعداء الغابة تحميل برامج Download DivX Subtitles 2.0 BullGuard 8.5 Google Chrome 2.0.181.1 Dev Dell Studio XPS Desktop 435T Intel Matrix Storage Manager A00 Gigabyte GA-EP45-UD3P Bios F9 Ambush HDConvertToX 1.1.229.1764 MSI Wind Nettop CS 120 Realtek Audio Driver 5.10.0.5618 Biostar T41-A7 6.x Realtek On-Board Audio Driver 5.10.0.5735 for 2000/2003/XP TweakNow RegCleaner 4.1.1 SpeedItup Free 4.97 برامج العاب - Internet Download Manager - برامج جوالات - العاب - محطة غنوة - قنوات فضائية - بنات - تكنولوجيا - كتب تعليم - UltraSurf - ق ذ -0

jiji530 replied on Mon, 2009/06/29 - 9:42pm

thanks for your post.perhaps you will like abercrombie ed hardy mortgage rates tiffanys ed hardy Is not it?

wikaniko replied on Thu, 2009/07/09 - 1:02pm

Thank you. You would not beleive how useful this has been. It is almost exactly what I was looking for :) I'm slowly coming to grips with JBoss. I come from a Jbuilder Background and before that JAVAC/Textpad. Big thanks for this article. John, Eco Products, UK.

superpan3721 replied on Sat, 2009/08/01 - 1:38am

The topic may be a bit too difficult for me to understand. New Balance

nakul replied on Tue, 2009/10/20 - 1:49pm in response to: thejavafreak

Thanks for explaining JBoss AOP it was really such a help i had many doubts and misconception most of them have been cleared now. Thanks. church chairs

markgrant1st replied on Wed, 2009/11/04 - 2:27am

Wish I could learn the programming . I know each and everything about the Markets but computer, me and computer can not be friends at all :)\

Home Insurance Rates

Teddy P replied on Thu, 2009/11/05 - 9:46am

Thanks for the ips. It will help out with my business. Locksmith Charlotte | Licensed Locksmith | Charlotte Locksmith

abcdentist replied on Sun, 2009/11/08 - 2:57am

JBoss AOP is a 100% Pure Java aspected oriented framework usuable in any programming environment or tightly integrated with our application server. Aspects allow you to more easily modularize your code base when regular object oriented programming just doesn't fit the bill. It can provide a cleaner separation from application logic and system code. It provides a great way to expose integration points into your software. Combined with JDK 1.5 Annotations, it also is a great way to expand the Java language in a clean pluggable way rather than using annotations solely for code generation. invisalign Birmingham

hpmedia replied on Sun, 2009/11/08 - 8:44pm

Tom Marrs, a 20 year veteran in the software industry, is the principal and senior software architect at Vertical Slice, a consulting firm that designs and implements mission-critical business applications using the latest J2EE and open source technologies. Tom speaks regularly at software conferences such as JavaOne and No Fluff Just Stuff. He is an active participant in the local technical community, and served as president of the Denver Java Users Group. white noise

hpmedia replied on Tue, 2009/11/17 - 5:40pm

Tom Marrs, a 20 assemblage stager in the code industry, is the principal and grownup code architect at Vertical Slice, a consulting concern that designs and implements mission-critical activity applications using the sharp J2EE and Ocean Sounds unstoppered anxiety technologies. blackamoor speaks regularly at code conferences such as JavaOne and No Fluff Just Stuff. He is an active participant in the topical theoretical community, and served as president of the Denver Java Users Group.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.