O'Reilly logo

AspectJ Cookbook by Russ Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.2. Developing a Simple Aspect

Problem

You want to write a simple aspect.

Solution

First, write your business logic classes, as shown in Example 2-1.

Example 2-1. A simple business logic Java class

package com.oreilly.aspectjcookbook;

public class MyClass
{
        public void foo(int number, String name)
        {
                System.out.println("Inside foo (int, String)");
        }

        public static void main(String[] args)
        {
                // Create an instance of MyClass
                MyClass myObject = new MyClass( );
                // Make the call to foo
                myObject.foo(1, "Russ Miles");
        }
}

Define an aspect that will be applied to this class. The aspect in Example 2-2 parodies the traditional “Hello World” for AspectJ by providing an aspect that captures all calls to the void foo(int, String) method in the MyClass class.

Example 2-2. A simple HelloWorld aspect in AspectJ

package com.oreilly.aspectjcookbook;

public aspect HelloWorld 
{
   pointcut callPointcut( ) : 
      call(void com.oreilly.aspectjcookbook.MyClass.foo(int, String));

   before( ) : callPointcut( )
   {
      System.out.println(
         "Hello World");
      System.out.println(
         "In the advice attached to the call pointcut");
   }
}

Save this file in the same directory as your business logic class as HelloWorld.aj or HelloWorld.java. Run the ajc command to compile this simple application and produce the byte code .class files for both the aspect and the class:

> ajc -classpath %MY_CLASSPATH% -d %MY_DESTINATION_DIRECTORY% com/oreilly/
aspectjcookbook/MyClass.java com/oreilly/aspectjcookbook/HelloWorld.java

If you get the following message then ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required