Skip to main content
  • Sign in (or register)
  • Englishspacer
  • spacer [userid]
  • spacer

By clicking Submit, you agree to the developerWorks terms of use.

  • Need an IBM ID?
  • Forgot your IBM ID?
  • Forgot your password?
  • Change your password

The first time you sign into developerWorks, a profile is created for you. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

  • spacer

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • spacer

My developerWorks:

  • My profile
  • My home
  • My groups

My notifications:

  • {[num_notify] new notifications}([num_notify] new notification)
  • {[num_invite] network requests}([num_invite] network request)
  • Sign out
  • spacer

Select a language:

  • English
  • 中文
  • 日本語
  • Русский
  • Português (Brasil)
  • Español
  • Việt
  • spacer
  • IBM home
  • Solutions
  • Software
  • Software services
  • Support
  • Product information
  • Redbooks
  • spacer

Technical topics

  • Agile transformation
  • AIX and UNIX
  • Business analytics
  • Business process management
  • Cloud computing
  • Commerce
  • IBM i
  • Industries
  • Information management
  • Java technology
  • Linux
  • Lotus
  • Mobile development
  • Open source
  • Rational
  • Security
  • Service management
  • SOA and web services
  • Tivoli
  • Web development
  • WebSphere
  • XML
  • Technical library
  • Products A to Z
  • spacer

Evaluation software

  • Information management
  • Lotus
  • Rational
  • Tivoli
  • WebSphere
  • More IBM products
  • spacer

Community

  • My home
  • Profiles
  • Groups
  • Blogs
  • Bookmarks
  • Forums
  • Wikis
  • Files
  • Activities
  • Podcasts
  • IBM Champion program
  • spacer

Events

  • Briefings
  • Webcasts
  • Find events (briefings, webcasts, conferences...)
  • spacer
  • developerWorks
  • Java technology
  • Technical library

AOP@Work: AOP and metadata: A perfect match, Part 1

Concepts and constructs of metadata-fortified AOP

Ramnivas Laddad (ramnivas@aspectivity.com), Principal, Aspectivity
Ramnivas Laddad is an author, speaker, consultant, and trainer specializing in aspect-oriented programming and J2EE. His most recent book, AspectJ in Action: Practical aspect-oriented programming (Manning, 2003), has been called the most useful guide to AOP/AspectJ. He has been developing complex software systems using technologies such as the Java platform, J2EE, AspectJ, UML, networking, and XML for over a decade. Ramnivas is an active member of the AspectJ user community and has been involved with aspect-oriented programming from its early form. He speaks regularly at conferences such as JavaOne, No Fluff Just Stuff, Software Development, EclipseCon, and O'Reilly OSCON. Ramnivas lives in Sunnyvale, California. You can find more about Ramnivas from his Web site: ramnivas.com.

Summary:  In this first half of a two-part article, author Ramnivas Laddad provides a conceptual overview of the new Java™ metadata facility and shows where AOP could most benefit from the addition of metadata annotations. He then walks you through a five-part design refactoring, starting with a metadata-free AOP implementation and concluding with one that combines the Participant design pattern with annotator-supplier aspects.

View more content in this series

Date:  08 Mar 2005
Level:  Intermediate
Also available in:   Russian

Activity:  15266 views
Comments:   spacer spacer

The new Java metadata facility, a part of J2SE 5.0, is perhaps the most significant addition to the Java language to date. By providing a standard way to attach additional data to program elements, the metadata facility has the potential to simplify and improve many areas of application development, including configuration management, framework implementation, and code generation. The facility will also have a particularly significant impact on aspect-oriented programming, or AOP.

The combination of metadata and AOP raises important questions, including:

  • What is the impact of the metadata facility on AOP?
  • Is metadata-fortified AOP optional, or is it necessary?
  • What are the guidelines for using metadata effectively with AOP?
  • How will this combination affect the adoption of AOP?

I'll begin to answer these questions in this two-part article, the second in the new AOP@Work series. In this first half of the article I'll start with a conceptual overview of metadata and the new Java metadata facility. I'll also explain the difference between supplying metadata and consuming it, and provide some common programming scenarios that invite the use of metadata annotation. Next, I'll quickly review the basics of AOP's join point model and explain where it would benefit from metadata fortification. I'll conclude with a practical example, evolving a design through five stages using metadata-fortified AOP. In Part 2, I'll demonstrate a novel way to view metadata as a signature in a multidimensional concern space, talk about the impact of metadata on AOP adoption, and conclude with some guidelines for effectively combining AOP and metadata.

Throughout the the article I'll put the concepts presented into practice using examples from three of the leading AOP implementations: AspectJ, AspectWerkz, and JBoss AOP. See Resources for a listing of introductory articles about the Java metadata facility and aspect-oriented programming.

Metadata concepts

Metadata is data about data. In the programming language context, metadata is additional information attached to program elements such as methods, fields, classes, and packages. Metadata is expressed using program elements called annotations. The semantics associated with metadata range from mere documentation to execution-behavior modification. For example, you could use metadata to describe the author and the copyright holder of a class, in which case it would have no effect on program execution; or you could use it to describe method properties such as transactionality characteristics, which would likely modify the behavior of the method, as I'll explain later in the article.

About this series

The AOP@Work series is intended for developers who have some background in aspect-oriented programming and want to expand or deepen their knowledge. As with most developerWorks articles, the series is highly practical: you can expect to come away from every article with new knowledge that you can put immediately to use.

Each of the authors contributing to the series has been selected for his leadership or expertise in aspect-oriented programming. Many of the authors are contributors to the projects or tools covered in the series. Each article is subjected to a peer review to ensure the fairness and accuracy of the views expressed.

Please contact the authors individually with comments or questions about their articles. To comment on the series as a whole, you may contact series lead Nicholas Lesiecki. See Resources for more background on AOP.

While there are numerous metadata tools for the Java language (XDoclet being the most well known), metadata annotations have only been incorporated into the core Java language with Java 5.0. The Java metadata facility (JSR 175; see Resources) includes a mechanism for adding custom annotations to your Java code, as well as providing a programmatic access to metadata annotation through reflection.

Key to understanding and using metadata are the concepts of supply and consume. A metadata supplier is a facility that associates annotation instances with program elements, whereas a consumer is a facility that reads, interprets, and acts on the annotation instances. In the next sections I'll discuss these concepts in more detail.

Supplying metadata

A metadata facility defines a mechanism to supply annotations to program elements. Optionally, a metadata facility can specify a way to define annotation types. Annotation types specify a template to create annotation instances, much the same way classes specify a template to create objects. The metadata facility can then check annotation instances against the annotation types. A metadata facility may also specify a general way to consume annotations. One thing a metadata facility does not do is define the interpretation and semantics associated with annotations. That is left up to the consumer, as I'll discuss in the next section.

The capabilities of metadata facilities vary. For example, the Javadoc specification allows you to specify annotations in the comments associated with a program element. Alternatively, some metadata facilities use a separate document (often an XML document) to express metadata. For example, EJB deployment descriptors specify additional characteristics of enterprise beans. Unlike the Javadoc facility, this approach loosely couples program elements and metadata; on the downside, it requires developers to modify multiple sources describing the same element.

The Java metadata facility adds new language support for metadata to declare annotation types and annotate program elements. It also makes it possible to retain metadata at source code level in class files, and at runtime controlled by a retention policy.

The supplier of metadata may include a facility to attach certain annotations in a crosscutting manner rather than individually supplying them to multiple elements. Due to the crosscutting nature of such annotations, AOP is a good way to supply them. I'll examine the details of such a facility later in this article.

The choice of metadata facility affects the experience of expressing metadata, but the fundamental idea of associating additional data to program elements is common to all metadata facilities.

Consuming metadata

Creating value from metadata annotations requires consuming them. Metadata can be consumed in a variety of ways, and understanding these uses will help put the combination of AOP and metadata into perspective. The following use cases should also help you understand how annotation supplied for non-AOP purposes can be consumed in an AOP implementation.

In the eye of the beholder

Metadata is additional information associated with program elements. What constitutes "additional," however, is subjective. Further, the target programming language influences what programmers consider to be inherent information about elements rather than metadata. For example, consider checked exceptions independent of the Java language. They could be though of as metadata that instructs the compiler. In fact, in languages without checked exceptions (such as C#), metadata is a good choice to convey the same information.

Similarly, in weakly typed languages even the argument and return types of a method could be expressed using metadata. Or consider the Java language without generics. Frameworks such as Hibernate and EJB use metadata to specify the same information that can be defined using Java generics. Even modifiers such as access specification could be considered metadata in these cases. In fact, if someone had seen the need sooner, chances are that the Java metadata facility's built-in @Override annotation would have been implemented with an extra modifier -- say the override keyword. The bottom line is that the difference between a program element and metadata depends on your perspective.

Code generation
Code generation is perhaps the most familiar way to use metadata. With XDoclet-like tools, you can consume annotations specified as Javadoc tags to produce artifacts such as XML documents or Java code. The generated code in turn affects the runtime behavior of the annotated elements. A new release of XDoclet that supports the Java metadata facility is being developed. The command-line utility apt (Annotation Processing Tool), a part of the Java 2 SDK 5.0 distribution, also provides a way to process annotations by writing plugins. For example, Contract4J, a recently released contract enforcement tool, uses apt to generate aspects to enforce design-by-contract (DBC) contracts.

Programmatic behavior modification
The standard metadata facility offers a way to keep annotation available at runtime. It also allows you to programmatically access annotation instances using reflection. The annotation instances can then be used much like other objects to modify the behavior of the program. Such programmatic consumption may also let programmers skip the code generation route for applications where the generated artifacts only allow information encoded in the annotations to be read.

Framework consumption
Metadata is commonly used to facilitate communication between program elements and frameworks or tools such as EJB, EMF, and TestNG. The framework itself may choose to use code generation, reflective access, or AOP to apply certain logic to execution. The proposed use of annotations in EJB 3.0, such as @Remove and @Session, communicates with the framework the role of the program element. The Eclipse Modeling Framework uses annotations (currently expressed as Javadoc tags) to create UML models and XML persistence support. And on the tool side, TestNG (for example) uses metadata to communicate between test cases and the test execution tool.

Language extension
This use of metadata extends the underlying programming language and the compiler. Associating semantic properties with metadata means that compiled classes may have a different structure and behavior from those without it (see Resources for a further discussion on this topic). The recently announced Pluggable Annotation Processing API (JSR 269 ) may lead to a standard way to process annotations for this purpose. The use of metadata to extend the Java language can be both powerful and dangerous: On the one hand, annotations allow us to add new features to the Java language without modifying the core language, thus making it an open language; in the best-case scenario, principled extensions could overcome some of the limitations of the host language. On the other hand, a nonstandard, ad hoc, or incoherent set of annotations could result in incomprehensible code.

Incidentally, enabling AOP within plain object-oriented languages is one example of using metadata for language extension. AspectWerkz and JBoss AOP use metadata to change the semantics of a class as an aspect, a data field as a pointcut, a method as an advice, and so on. AspectJ 5 will similarly support the @AspectJ syntax, which is a result of the merging of the AspectJ and AspectWerkz projects. See Resources to learn more about the different AOP implementations and Java language extension.

In the next section I'll quickly review the basics of AOP's join point model, then explain where it could be beneficially fortified with metadata.


Back to top

Metadata and the join point model

A join point is an identifiable point in the execution of a system. The join point model, the most fundamental and distinguishing concept in AOP, defines which join points in a system are exposed and how they are captured. To implement crosscutting functionality using aspects, you need to capture the required join points using a programming construct called a pointcut.

Pointcuts select join points and collect the context at selected join points. All AOP systems provide a language to define pointcuts. The sophistication of the pointcut language is a differentiating factor among the various AOP systems. The more mature the pointcut language, the easier it is to write robust pointcuts. See the first article in the AOP@Work series for a detailed discussion on the importance of pointcut language (reference in Resources).

Capturing join points

A pointcut specifies the properties of a given element of a program. A major portion of the art and science of writing good aspects lies in writing robust pointcuts; the other major portion being well-designed aspect inheritance. Pointcuts that capture more join points than expected or miss the expected join points can lead to a brittle implementation as the system evolves. Writing good pointcuts is key to mastering AOP, although it is often a struggle for newcomers.

Currently, the most common way to capture join points utilizes the implicit properties of program elements, including static properties such as signature (which consists of type and method name, argument types, return type and exception type, etc.) and lexical placement, as well as dynamic properties such as control flow. Judiciously using wildcards in join point signatures often leads to good, succinct pointcut definitions. You can also compose individual pointcuts to form more complex ones. The join point model based on implicit properties of program elements is both powerful and useful, as evidenced by the current success of AOP in several production systems.

The implicit information available in the signature of program elements is often enough to capture the required join points. In this model, sometimes called dynamic crosscutting, the combination of implicit data, wildcards, and dynamic properties such as control flow lets you capture join points without modifying the captured program elements. For example, you can capture all RMI calls by specifying operations throwing RemoteException in a class implementing the Remote interface. A pointcut such as execution(* Remote+.*(..) throws RemoteException) (defined in AspectJ) neatly captures all RMI operations without modifying the program elements, and also ensures a robust pointcut. The beauty here is being able to capture join points without additional collaboration beyond that required by the RMI infrastructure.

Capturing join points with metadata

Signature-based pointcuts cannot capture the join points needed to implement certain crosscutting concerns. For example, how would you capture join points requiring transaction management or authorization? Unlike the RMI example, nothing inherent in an element's name or signature suggests transactionality or authorization characteristics. The pointcut required in these situations can get unwieldy, as you can see for yourself in the following example. (The example is in AspectJ but pointcuts in other systems are conceptually identical.)

pointcut transactedOps() 
    : execution(public void Account.credit(..))
      || execution(public void Account.debit(..))
      || execution(public void Customer.setAddress(..))  
      || execution(public void Customer.addAccount(..))
      || execution(public void Customer.removeAccount(..));

Situations like this one invite the use of metadata to capture the required join points. For example, you could write a pointcut as shown below to capture the execution of all the methods carrying the @Transactional annotation.

pointcut execution(@Transactional * *.*(..));

Metadata and modularity

While the above example may make using metadata to capture join points seem like a no-brainer, it's important to consider the implications of such usage, particularly when it comes to modularity. Once you begin using metadata in your pointcuts, methods must carry the appropriate annotation to collaborate in the crosscutting implementation of aspects that use them, as shown here:

public class Account {
    ...

    @Transactional(kind=Required)
    public void credit(float amount)  {
        ...
    }

    @Transactional(kind=Required)
    public void debit(float amount)  {
        ...
    }
	
    public float getBalance() {
        ...
    }

    ...

}

Similarly, the addAccount(), removeItem(), and setAddress() methods in the Customer class now have to carry the @Transactional annotation.

Most AOP practitioners are currently implementing transactional and authorization concerns with existing AOP support, typically through the use of design patterns utilizing aspect inheritance. As you'll see in this article, however, adding metadata to AOP systems can improve them considerably. I'll talk more about how adding metadata effects the modularity of AOP systems, as well as the scenarios where metadata is most beneficial in Part 2 of this article. In the next section I'll begin to explain more concretely how AOP implementations can be extended to incorporate metadata.


Back to top

Metadata-fortified AOP

AOP systems and their join point models can be augmented by consuming metadata annotations. JBoss AOP, Spring AOP, AspectWerkz, and AspectJ all provide or plan to provide mechanisms to utilize metadata. JBoss AOP and AspectWerkz support metadata in their current versions. Spring AOP supports metadata by letting you write pointcuts programmatically, by implementing the org.springframework.aop.Pointcut interface. The upcoming version of AspectJ will support metadata by modifying the AspectJ language.

In the previous section I showed you the basics of how an AOP system can consume metadata, using the example of picking out methods with the @Transactional annotation. In this section and throughout the remainder of the article I'll focus on the specifics of combining AOP and metadata.

While the examples in this article focus on AOP implementations that support metadat

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.