Thursday, December 29, 2011

A Look Into Java Annotations & A Real World Spring Example

An "annotation" is a type of programminglanguage definition and used as a “marker”. They can be thought as commentlines which programming language engine can understand. They don’t directlyaffect program execution but affect indirecly if wanted.


An annotation is defined with @interface keyword and is similar withan interface. It has attributes which are defined like interface methods.Attributes can have default values. Let’s define an annotation named “Page”,which defines UI pages of an application:

public @interface Page {
    int    id();
    String url();
    String icon()default "[none]";
    String name();default "[none]";


Annotations are widely used to informcompiler or compile-time/runtime/deployment-time processing.
Usage ofan annotation is simpler:

@Page(id=1, url=”studentView”, icon=“icons/student.png”,name=”Students”)
public class StudentWindow extends Window { … }

Annotationscan also be defined for methods and attributes:

public String getElementName() {…}

@AnAnnotation(type=”manager”, score=3)
public int income;


1)   Reflection/code generation:

Methods havinga specific annotation can be processed at runtime:

public @interface MyAnnotation { ... }
public class TestClass {
    public static method1() { ... }
    public static method2() { ... }
    public static method3() { ... }

public static void main(String[] args) {
    for (Method method : Class.forName("TestClass").getMethods()) {
        if (method.isAnnotationPresent(MyAnnotation.class)) {
            // do what you want

2)   Spring bean configuration (this section requires Spring bean configurationknowledge):

Let’s useour “Page” annotation again:

package com.cmp.annotation;
public @interface Page {
    int    id();
    String url();
    String icon() default "[none]";
    String name(); default "[none]";

Say thatwe have a few classes having @Page annotation in a package:

@Page(id=1, url=”studentView”, icon=“icons/student.png”, name=”Students”)
public class StudentWindow extends Window { … }

If wedefine a bean configuration as below in a Spring application-context.xml file, Springwill create class instances “which has @Page annotation” placed in “givenpackage”.

<context:component-scan base-package="com.cmp.ui" annotation-config="true">
<context:include-filter type="annotation" expression="com.cmp.annotation.Page"/>

So, we havebeen enforced Spring to instantiate only a selection of classes at runtime.

For more detailed info about annotations, please refer to:

No comments:

Post a Comment