Second-generation aspect-oriented programming (1)

 

Second-generation aspect-oriented programming

Apply advice dynamically with the new crop of AOP frameworks

Summary
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

Advertisement
<script language=JavaScript src="http://spinbox.macworld.com/?DC=jw-BigBox&JS=Y&TARGET=_top&BA=1"></script>

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)
         ProxyFactory.instance().getProxy("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) {
      mContext.putAll(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.*(..)) {
      ServerSideContext.instance().setContext(
         ClientSideContext.instance().getContext());
   }
}

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
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值