Scope and placement of annotations

You can add annotations to your source code at the class, method, and field level.

Using Annotations

EJB 3.1 and the Java™ persistence API make use of metadata annotations, a feature that was introduced in J2SE 5.0. An annotation consists of the @ sign preceding an annotation type, sometimes followed by a parenthetical list of element-value pairs. The EJB 3.1 specification defines various annotation types, for example:
  • Component-defining annotation, such as @Stateless, which specifies the bean type
  • @Remote and @Local specify whether a bean is remotely or locally accessible
  • @TransactionAttribute specifies transaction attributes
  • @MethodPermissions, @Unchecked, and @SecurityRoles specify security and method permissions
The Java Persistence API adds annotations specific to the creation of entities, for example:
  • @Entity is a component-defining annotation that specifies that a class is an entity
  • @Table specifies the data source to be used in the class
Note: JPA mapping annotations (@Id, @Column, for example) can be applied to both fields and methods, but for any one entity class you can only apply them to one or the other; that is, either all annotations must be applied to fields, or they all must be applied to methods. Fields can only have private, protected or package visibility, and clients of an entity are not allowed to access the fields directly, so you need to define public getters and setters.
  • @MethodPermissions, @Unchecked, and @SecurityRoles specify security and method permissions

Scope and placement of annotations

Annotations operate at a class, interface, method, or field level. For example, component-defining annotations (like @Stateless or @Entity) are class-level annotations and they are inserted in the comments section before the class declaration:
package com.ibm.websphere.ejb3sample.counter;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
@Interceptors ( Audit.class )

public class StatelessCounterBean implements LocalCounter, RemoteCounter {
The order of these annotations is not significant; typically, the component-defining annotation is placed before other annotations, but this placement is not required. Method-level and field-level annotations appear within the class or method:
public class JPACounterEntity {

    @Id
    private String primarykey = "PRIMARYKEY";

    private int value = 0;
Icon that indicates the type of topic Concept topic
Timestamp icon Last updated: July 17, 2017 21:58

File name: cusingannotations.html