Second-generation aspect-oriented programming (1)

转载 2004年10月20日 12:36:00

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 friendMail 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

Second-generation aspect-oriented programming (3)

  Second-generation aspect-oriented programming Apply advice dynamically with the new crop of AOP fr...
  • jgo
  • jgo
  • 2004年10月20日 12:42
  • 1010

Second-generation aspect-oriented programming (2)

  Second-generation aspect-oriented programming Apply advice dynamically with the new crop of AOP fr...
  • jgo
  • jgo
  • 2004年10月20日 12:40
  • 803

Aspect-oriented programming

我们对面向过程和面向对象的编程语言已经耳熟能详了。 今天来看看Aspect-oriented programming,也就是面向行为的编程。 参考wiki,写的很不错: http://en....
  • OnlyQi
  • OnlyQi
  • 2011年12月31日 12:46
  • 2442

AOP( aspect-oriented programming)面向切面编程

AOP( aspect-oriented programming)面向切面编程 一、什么是AOP? 可以通过预编译方式和运行期动态代理实现在不修改源代码情况下给程序动态统一添加功能的一种技术。 ...
  • ly969434341
  • ly969434341
  • 2016年08月27日 19:45
  • 435

Second-generation aspect-oriented programming By Dave Schweisguth

Dynamic AOP with JBoss AOP JBoss AOP is an AOP implementation developed by JBoss. While it came out ...
  • WonderOne
  • WonderOne
  • 2004年12月21日 12:59
  • 1236

iOS 如何实现Aspect Oriented Programming (下)

(接上篇) 五. Aspects hook过程详解 先看看函数调用栈的情况 - aspect_prepareClassAndHookSelector(self, selector, error)...
  • qq_30513483
  • qq_30513483
  • 2016年10月27日 16:37
  • 514

Java 面向切面编程(Aspect Oriented Programming,AOP)

本文内容 实例 引入原始方法装饰者模式 JDK 动态代理和 cglib 代理直接使用 AOP 框架——AspectWerkz 新公司使用了 AOP 相关的技术,于是复习一下,没怎么...
  • wah001
  • wah001
  • 2017年07月09日 09:51
  • 159

AOP(面向切面编程 Aspect Oriented Programming)

AOP(面向切面编程 Aspect Oriented Programming)概念(百度百科) 通过 预编译方式和运行期动态代理 实现 程序功能 的 统一维护 的一种技术。特点:低耦合,高聚合。 A...
  • daisywangyy
  • daisywangyy
  • 2016年06月12日 10:01
  • 954

iOS 如何实现Aspect Oriented Programming (上)

前言 在“Runtime病院”住院的后两天,分析了一下AOP的实现原理。“出院”后,发现Aspect库还没有详细分析,于是就有了这篇文章,今天就来说说iOS 是如何实现Aspect Oriented...
  • qq_30513483
  • qq_30513483
  • 2016年10月27日 16:36
  • 712


About the Project The success of Aspect-Oriented Software Development rises and falls with user-fri...
  • gxp
  • gxp
  • 2012年03月13日 14:59
  • 726
您举报文章:Second-generation aspect-oriented programming (1)