Section 21.2. What Are Code Annotations?


21.2. What Are Code Annotations?

If you write Java code and document your code (one doesn't necessarily imply the other, sadly), you are already familiar with a particular kind of code annotation: Javadoc tags. With Javadoc, you put metadata about the code (like the author, references to other related classes, and descriptions of the meanings of methods) into the code itself, in the form of annotations. You then run a tool (in this case, the Javadoc generator) over the code to generate HTML documentation from these annotations.

Generalized annotation schemes follow this same basic model. The difference is that you can do much more than just generate documentation (as useful as that is). Code annotations can be used to generate deployment descriptors, configuration files, and even Java code, as shown in Figure 21-1.

Figure 21-1. General model for code annotations


As depicted in the figure, annotations are inserted as markup directly in your code. As an example, here's an XDoclet annotation specifying some deployment settings for a web component:

 /**  * @web.servlet  *     name="ShoppingCart"  *     display-name="The Shopping Cart Servlet"  */ public class ShoppingCartServlet extends HttpServlet {     . . . } 

When you're dealing with enterprise development scenarios, annotating your code in a structured way can benefit you in a number of ways:


Reduce development effort

An annotation system allows you to mark up your code directly and then use this markup information to automatically generate all the trappings required for the context at hand. A deployment descriptor, for example, can be generated using some basic settings provided in a set of code annotations. The annotation processor can generate the proper XML structure and insert default values for any unspecified but required deployment settings.


Simplify code management

Annotations are embedded in the code, which makes tracking, updating, and finding key metadata about the code much easier. Similar to the principle of Javadoc annotations for documentation, keeping the metadata with the code makes it much easier to keep the information in line with the current state of the code and vice versa.


Make your code more flexible

If you use annotations consistently across your project code, they can be a significant aid when it comes time to refactor your code in certain ways. If, for example, you consistently generate deployment descriptors using annotations, you can very easily deploy your code to various types and versions of J2EE application servers simply by altering the parameters used by the annotation processor.



Java Enterprise in a Nutshell
Java Enterprise in a Nutshell (In a Nutshell (OReilly))
ISBN: 0596101422
EAN: 2147483647
Year: 2004
Pages: 269

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net