Using Singleton Aspects
By default, AspectJ aspects are singletons, in that you get a single instance per classloader. The problem
Spring faces with any AspectJ aspect is that it cannot create the aspect instance because that is handled
by AspectJ itself. However, each aspect exposes a method, aspectOf() (which is from the
org.aspectj.lang.Aspects class within the aspectjrt jar library), which can be used to access the aspect
instance. Using the aspectOf() method and a special feature of Spring configuration, you can have
Spring configure the aspect for you. The benefits of this cannot be understated. You can take full
advantage of AspectJ's powerful AOP feature set without losing out on Spring's excellent DI and
configuration abilities. This also means you do not need two separate configuration methods for your
application; you can use the same Spring ApplicationContext approach for all your Spring-managed
beans and for your AspectJ aspects.
There is actually nothing particularly special or difficult about configuring AspectJ aspects using
Spring, as the following example shows. In Listing 7-31, you can see a basic class, MessageWriter, that we
will advise using AspectJ.
Listing 7-31. The MessageWriter Class
package com.apress.prospring3.ch7.aspectj;
public class MessageWriter {
public void writeMessage() {
System.out.println("foobar!");
}
public void foo() {
System.out.println("foo");
}
}
For this example, we are going to use AspectJ to advise the writeMessage() method and write out a
message before and after the method invocation. These messages will be configurable using Spring.
STS bundled the AspectJ Development Tools, which is an Eclipse plug-in for AspectJ development.
We will use it to develop the example AspectJ aspect. To enable AspectJ support for the project, right-
click the project and select Configure Convert to AspectJ Project. Figure 7-5 shows the STS menus.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home