img jgo

Second-generation aspect-oriented programming (1)

发表于2004/10/20 12:36:00  1039人阅读

分类: Java基础


Second-generation aspect-oriented programming

Apply advice dynamically with the new crop of AOP frameworks

While aspect-oriented programming (AOP) offers a powerful means of modularizing programs, and a robust, feature-rich implementation for the Java platform is available in AspectJ, AOP is not yet in the average Java programmer's toolbox. AOP has remained an interesting curiosity at conferences and an item on everyone's to-do list to learn more about—until now. In the last year, a wave of interest in lightweight, transparent application servers has washed up a whole school of new AOP implementations, with features that allow developers to apply advice more dynamically and flexibly than before. In this report on the new generation of AOP frameworks, Dave Schweisguth contrasts the new with the old, explains where the new features fit in, and looks to the future of AOP on the Java platform. (3,400 words; July 5, 2004)
By Dave Schweisguth

Printer-friendly version
Printer-friendly version | Send this article to a friend Mail this to a friend

Page 1 of 3


Modularization makes programming possible. Throughout the history of computing, a parade of organizational devices—the high-level language, the subroutine, the object—has allowed us to write increasingly more expressive and powerful code. But, just as with computer hardware, when our abilities improve, we raise the bar again, and here in the twenty-first century, we still struggle to quickly and cheaply produce large programs. What is the next step, the new way to structure our programs that will take our abilities to the next level?

Aspect-oriented programming (AOP) is one attempt at an answer. Conceived at Xerox PARC (an auspicious pedigree!) in the late 1990s, AOP intends to modularize cross-cutting concerns: lines of code that would have to be repeated throughout an ordinary program. AOP gathers all of these cross-cutting concerns into a single place, an AOP construct similar to a class, known as advice.

AspectJ, also originally from Xerox PARC and now developed by the Eclipse Foundation, is an implementation of AOP for the Java platform. It is a mature and solid framework that has gone through several significant releases and is even supported by some third-party tools. Recently, however, application server designers have realized that while—just as AOP proponents have been saying for years—AOP seems a natural way to implement many kinds of application server functionality such as remoting, persistence, and transactions, AOP would be much easier to use in the dynamic environment of the Java platform if its implementation were equally dynamic.

For a thorough introduction to AOP concepts and the AspectJ implementation, see Ramnivas Laddad's three-part JavaWorld series, "I Want My AOP!". For this discussion, I assume you're up to speed on AOP basics and briefly present classic AOP examples so we can get on to the new stuff.

Old-school AOP with AspectJ
Here's an example of how aspect-oriented programming might be used in a middleware framework: Imagine that in our framework, a client accesses services via proxies. The services might be in another VM and might be reached by any remoting technology; hiding these things from the client is the framework's reason for being. One of our framework's features is its ability to propagate any context that a developer wishes from the client to the services it calls transparently to the client. For example, an application might log a user into a security service and put an authentication token in the context. From then on, any services called by that application would be able to retrieve the authentication token from the context—on the server side—and use it to control the functionality to which the client has access.

First, let's write a simple test to show that context is propagated:

public class ContextPassingTest extends TestCase {
   public void test() {
      ClientSideContext.instance().put("userID", "dave");
      ContextRetriever proxy = (ContextRetriever)
      assertEquals("dave", proxy.get("userID"));

In our test, we first put an authentication token into the context. Next, we get a proxy to our service from a singleton ProxyFactory. (This is an example of the Service Locator pattern, in which a factory hides from the client the complexity of constructing a proxy to a remote service.) The service, an instance of ContextRetriever, simply returns the requested value from its context. In the test's last line, we ask for our authentication token back and test to see whether it has the value it should. That's it!

As with any nice compact example, a couple of comments are in order. First, note that while this test may seem rather pointless, in a real application, we would read from the context in a place different from where we would write to it and actually use context information on the server side instead of just sending it back.

Second, note that, although this example uses the Singleton pattern in several places because it is well known and succinct, if you ever find yourself writing a widely used framework, you should certainly not use the Singleton pattern in its API. Singleton requires the singleton instance to be a concrete class, whereas interesting classes should always be hidden behind interfaces to allow the implementations to be swapped without affecting clients. Furthermore, since the singleton reference is global, it proves difficult to make an object use a different instance when necessary, such as in testing. (See "Use Your Singletons Wisely" for more on this topic.) Having warned you about the Singleton pattern, I return to using it for brevity, but don't take it to heart.

Now let's look at the classes our test uses. ClientSideContext is simply a singleton wrapper around a HashMap, a place to store context until it's needed:

public class ClientSideContext {
   private static final ClientSideContext INSTANCE = new ClientSideContext();

   public static ClientSideContext instance() {
      return INSTANCE;

   private final Map mContext = new HashMap();

   public void put(Object key, Object value) {
      mContext.put(key, value);

   public Map getContext() {
      return mContext;


The ContextRetriever interface (not shown; see Resources for complete source code) has a single method, get(Object). In this simple example, ProxyFactory (also not shown) just creates and returns an instance of the following ContextRetriever implementation:

public class ContextRetrieverImpl implements ContextRetriever {
   public Object get(Object key) {
      return ServerSideContext.instance().get(key);

ContextRetrieverImpl delegates to a singleton instance of ServerSideContext, which is similar to ClientSideContext but is used on the server side:

public class ServerSideContext {
   private static final ServerSideContext INSTANCE = new ServerSideContext();

   public static ServerSideContext instance() {
      return INSTANCE;

   private final Map mContext = new HashMap();

   public void setContext(Map context) {

   public Object get(Object key) {
      return mContext.get(key);


So, how does the context get from client to server? With the following aspect:

aspect ContextPasser {
   before(): execution(* ContextRetrieverImpl.*(..)) {

This aspect contains a single piece of advice. The advice is before() advice, which runs before the method being advised. The execution() statement determines the methods before which the advice runs. In this case, the expression ContextRetrieverImpl.*(..), referred to as a pointcut, causes the advice to run before any method of the class ContextRetrieverImpl. In the advice's body, where the actual work is done, we finally see how our context is passed: the entire context is copied from ClientSideContext to ServerSideContext. In a real framework, of course, the server side might be in another VM and we'd have a bit more work to do, but our short version illustrates the point.

Writing our context-passing functionality in an aspect gives us some nice advantages over a conventional object-oriented design. It reduces the dependencies from the client and server sides to the context-related classes, without requiring the service to implement an interface (as an EJB (Enterprise JavaBean) component must do to receive a SessionContext). We've actually decoupled context passing from the rest of the framework; so, if for some reason we don't need context passing—perhaps, in some applications, we intend to use only services that don't need context—we can recompile the application without the ContextPasser aspect. The test above will fail, but everything will compile, and code that doesn't require context to be passed will work just fine without the overhead of passing unused context. This is exactly the sort of modularization that AOP was intended to provide. And we don't need to stop here: security enforcement code and even the proxying itself can be moved into aspects as well.

Next page >
Page 1 Second-generation aspect-oriented programming
Page 2 An AOP wish list
Page 3 Dynamic AOP with JBoss AOP
0 0


取 消