What is an annotation?
An annotation is a class member, the purpose of which is to describe other members of the class. The literal meaning of the word annotation is: a note added to describe or clarify something. In real life we all use annotations. When you write the meaning of a word over it at the time of reading a book, you are actually annotating the word.
Why annotations are required?
A web server, framework or runtime environment which manages user defined classes, need some configuration information to manage them. Conventionally configuration information is provided in XML format e.g. in a web application, web.xml file is used to provide the configuration of servlets, listeners and filters to the web server. XML based configuration has following drawbacks:
1. A separate configuration file need to be maintained in the application.
2. More words are used to describe the configuration than the configuration itself. Such description is called verbose. e.g. in the following web.xml file configuration information is of two words (S1 & WelcomeServlet) rest of the information (<web-app>, <servlet>, <servlet-name>, <servlet-class> and their closing elements) is the description of the configuration.
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>com.techmentro.learningpad.WelcomeServlet</servlet-class> </servlet> </web-app>
Annotations were introduced in Java 5 to be an alternative to XML based configuration. Annotations remove both the drawbacks of XML based configuration.
1. Addition of the configuration directly to the class and its members in the form of annotations, eliminate the need of separate configuration file.
2. When the configuration is directly added to a class or its member then no additional description is required i.e. annotations based configuration is concise in comparison to XML based configuration.
Following diagram describes, how annotations based configuration is used by servers, frameworks and run time environments:
Description of the diagram:
Types of annotations:
Annotations are of two types: Marker & Non-Marker. The difference between these two, is of parameters. Marker annotations don’t accept parameters whereas non-marker do. Parameters are used to provide additional information as part of the annotation.
Limitation of annotations:
As XML based configuration has limitations similarly, annotations do have following limitations:
In 3rd release of servlet API, following annotations were introduced to be used for providing the configuration of web application components to the web servers.
In a servlet 3 API compatible web application, configuration can be provided:
1. –Through web.xml as before.
2. – Through annotations.
3. – Through both web.xml as well as annotations.
In the next post, practical use of the servlet annotations will be demonstrated.