Anotations basic use 1

The official summary of annotation is as follow: As of release JDK 5.0, the platform has a general purpose annotation (also known as metadata) facility that permits you to define and use your own annotation types.

 

Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the interface keyword. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. Methods can have default values. Here is an example annotation type declaration.

 

/**

 * Describes the Request-For-Enhancement(RFE) that led

 * to the presence of the annotated API element.

 */

public @interface RequestForEnhancement {

    int    id();

    String synopsis();

    String engineer() default "[unassigned]";

    String date();    default "[unimplemented]";

}

 

In annotations with a single element, the element should be named value, as shown below:

/**

 * Associates a copyright notice with the annotated API element.

 */

public @interface Copyright {

    String value();

}

 

Applying Annotation with other framework

Annotation has been extensively used in Spring and other frameworks. In this note, I am only introducing very small portion based on a unit test demonstration.

 

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = {"/test-datasources.xml", "/ioc/app-config.xml"})

public abstract class AbstractAnnotationDaoTest {

    @Autowired

    public SessionFactory sessionFactory;

}

 

·          @RunWith  When a class is annotated with @RunWith or extends a class annotated with @ RunWith, JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit.

 

·          @ContextConfiguration defines class-level metadata which can be used to instruct client code with regard to how to load and configure an ApplicationContext. Variable “locations” specifies where to load it. (Make sure you inculde all configurations that used for test, such as test  datasource)

 

·          @Autowired more details are explained later. Basically, BeanFactory will be autowired into a field, constructor argument, or method parameter that is expecting the BeanFactory type as long as the field, constructor, or method in question carries the @Autowired annotation. in the preceding example, the value of sessionFactory will injected, based on its definition in the app-config.xml file. (This property is just for demonstration purpose and not used in the following sub class)

 

public class NewsDaoTest extends AbstractAnnotationDaoTest {

    @Resource

    private NewsDao newsDao;

 

    @Test

    public void getLastMonthNews () {

        List<Document> list = this.newsDao.getLastMonthNews();

        assertNotNull(list);

    }

}

 

·          @Resource is from Java annotation, you can replace with @autowired from spring framework as introduced above.  I couldn’t see the virtual difference between the two. The description of @Resource from its official JavaDoc is as follow: The Resource annotation marks a resource that is needed by the application.  This annotation may be applied to an application component class, or to fields or methods of the component class.  When the annotation is applied to a field or method, the container will inject an instance of the requested resource into the application component when the component is initialized.

·          @Test tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method.

 

 

 

 

 

Autowiring collaborators explanation on Spring framework site

The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes. Autowiring is specified per bean and can thus be enabled for some beans, while other beans will not be autowired

 

Mode

Explanation

no

No autowiring at all. Bean references must be defined via a ref element. This is the default, and changing this is discouraged for larger deployments, since explicitly specifying collaborators gives greater control and clarity. To some extent, it is a form of documentation about the structure of a system.

byName

Autowiring by property name. This option will inspect the container and look for a bean named exactly the same as the property which needs to be autowired. For example, if you have a bean definition which is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring will look for a bean definition named master, and use it to set the property.

byType

Allows a property to be autowired if there is exactly one bean of the property type in the container. If there is more than one, a fatal exception is thrown, and this indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set. If this is not desirable, setting the dependency-check="objects" attribute value specifies that an error should be thrown in this case.

constructor

This is analogous to byType, but applies to constructor arguments. If there isn’t exactly one bean of the constructor argument type in the container, a fatal error is raised.

autodetect

Chooses constructor or byType through introspection of the bean class. If a default constructor is found, the byType mode will be applied.

 

Note that explicit dependencies in property and constructor-arg settings always override autowiring. Please also note that it is not currently possible to autowire so-called simple properties such as primitives, Strings, and Classes (and arrays of such simple properties).

 

Reference

http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-autowired-annotation  

http://static.springframework.org/spring/docs/2.5.x/reference/metadata.html

http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html

 

Advertisements
This entry was posted in Spring. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s