Java EE Annotation – extensive overview

Egmont-Petersen

Java J2EE – Enterprise Edition – EE 6/7

Compiled by Michael Egmont-Petersen, 19-01-2016.

Enterprise systems (EPS) can run as a Java Enterprise Applications (Java EE 6/7), under Glassfish/Payara or JBoss/Wildfly. Java Enterprise (EE or J2EE) is a complex and large-scale software framework, an extension to the standard set of Java technology being used in small to medium sized applications. Several tutorials exist, see for example Java EE 7.

Java EE was designed and developed over the last 15 years to facilitate design, development, deployment and daily operations of large-scale web-servers. Scale here refers to the number of Http-requests that can be handled in parallel, and the processing power that is made available by multi-threaded beans (servlets), facilitated by instantiated (ready-to-use) thread-pools.Enterprise applications also require access to a relational database that is geared to handle all the requests and large amounts of data, with sufficient speed for all data-producing and data-consuming services to run with the required speed.

Java Enterprise is the ‘larger brother’ of Spring. These two software frameworks compete on the professional Java-server market.

 

Multi-tier applications
Java EE applications are multi-tier meaning that different layers of the software are successively invoked when an Http-request is received by the webserver.

The servlets are the back-end Java beans that implement the business logic and communicate directly with the relational database. Enterprise beans are server-side components designed to encapsulate business logic in a manner decoupled from any one specific application client. By implementing your business logic within enterprise beans you will be able to reuse those beans in multiple applications.

[Illustration obtained from: source]

Tiers present:
• Client-tier (Application client/web pages)
• Web-tier (typically JSP)
• Business tier (servlets/beans)

A central concept in Java EE is the Java Bean, or just Bean.

See tutorial on Java Enterprise Beans.

One also talks about POJOs (Plain Old Java Objects), meaning Java classes. In daily practice, the Java EE developer needs to add pragma-statements to the Java-classes, in order to indicate the way the Java Bean operates.

See page on EE annotations.

 

Commonly used EE pragma statements (@-annotation) include:

@ApplicationScoped: This means that an instance will be created only once for the duration of the whole application. (Try changing the @ApplicationScoped annotation to @RequestScoped and see what happens).
@Asynchronous: Session beans can implement asynchronous methods, business methods where control is returned to the client by the enterprise bean container before the method is invoked on the session bean instance. Clients may then use the Java SE concurrency API to retrieve the result, cancel the invocation, and check for exceptions. Asynchronous methods are typically used for long-running operations, for processor-intensive tasks, for background tasks, to increase application throughput, or to improve application response time if the method invocation result isn’t required immediately.
When a session bean client invokes a typical non-asynchronous business method, control is not returned to the client until the method has completed. Clients calling asynchronous methods, however, immediately have control returned to them by the enterprise bean container. This allows the client to perform other tasks while the method invocation completes. If the method returns a result, the result is an implementation\of the java.util.concurrent.Future<V> interface, where “V” is the result value type.
The Future<V> interface defines methods the client may use to check whether the computation is completed, wait for the invocation to complete, retrieve the final result, and cancel the invocation.
Note that a container-based database transaction is not completed (no ‘commit’ takes place), before the asynchronous method is finalized.
Asynchronous methods can be used as background jobs. Hence, several consecutive calls to an Asynchronous method each time starts a parallel job (thread).
@EJB: Indicates a dependency on the local, no-interface, or remote view of an Enterprise JavaBean.
Either the beanName or the lookup element can be used to resolve the EJB dependency to its target session bean component. It is an error to specify values for both beanName and lookup.
If no explicit linking information is provided and there is only one session bean within the same application that exposes the matching client view type, by default the EJB dependency resolves to that session bean.
@Stateless: A stateless session bean does not maintain a conversational state with the client.
When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client but only for the duration of the invocation. When the method is finished, the client-specific state should not be retained.
@Singleton: A Singleton session bean is instantiated once per application
and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across
and concurrently accessed by clients.
@LocalBean: Bean has a @LocalBean annotation -> bean has a no-interface view.
A local bean is typically used for processing, i.e. by a standard Java class.
This can be a batch job or simply function calls that respond to events received by another bean.
Remote client view
When your EJB and its clients will be in a distributed environment – meaning EJBs and clients will reside on separate Java virtual machines. Example : EJBs hosted on a WebSphere Application Server and Servlets that consume EJB APIs
hosted on a Tomcat server.
Local client view
Only when it is guaranteed that other enterprise beans or clients will only address the bean within a single JVM. Example, EJBs as well as
the Servlets deployed on the same WebSphere server.
No-Interface view
Is almost same as local client view, but there are differences. Your bean class is not required to implement client view interfaces in this case.
All public methods of the bean class are automatically exposed to the caller. no-interface view always acquires an EJB reference – just like local or remote views – either through injection or JNDI lookup; but, Java type of the EJB reference is the bean class type rather than the type of a local interface.
This is a convenience introduced as part of Java EE6.
Difference between local client view and no-interface view
In case of no-interface view, the client and the target bean must be packaged in the same application (EAR). In case of local view,
client can be packaged in a separate application than the enterprise application. So, this gives more flexibility in terms of fine-grining your components. You may use local client view vs no-interface view depending on your API usage scenario.
It is very likely for no-interface view to receive flexible features in future specs. See in-depth explanation on views.
@MessageDriven: A message-driven bean, see tutorial on message-driven beans, is an enterprise bean that allows Java EE applications
to process messages asynchronously. This type of bean normally acts as a JMS message listener, which is similar to an event listener but receives JMS messages instead of events. See also tutorial on Session Beans

@ManagedBean: A managed bean is implemented by a Java class, which is called its bean class.
A top-level Java class is a managed bean if it is defined to be a managed bean by any other
Java EE technology specification, such as the JavaServer Faces technology specification,
or if it meets all the following conditions: (It is not a nonstatic inner class. It is a concrete class or is annotated @Decorator,
It is not annotated with an EJB component-defining annotation or declared as an EJB bean class in ejb-jar.xml,
It has an appropriate constructor. That is, one of the following is the case:
The class has a constructor with no parameters; The class declares a constructor annotated @Inject, No special declaration, such as an annotation, is required to define a managed bean.)
@Entity: We use the name attribute of the @Entity annotation to provide
an explicit entity name to match with the database table name.
@Startup: Mark a singleton bean for eager initialization during the application startup sequence.
@PostConstruct: The PostConstruct annotation is used on a method that needs to be executed after dependency injection
is done to perform any initialization. This method MUST be invoked before the class
is put into service. This annotation MUST be supported on all classes that support dependency injection.
The method annotated with PostConstruct MUST be invoked even if the class does not request
any resources to be injected. Only one method can be annotated with this annotation.
The method on which the PostConstruct annotation is applied MUST fulfill all
of the following criteria
– – The method MUST NOT have any parameters except in the case of EJB interceptors in which case it takes an InvocationC ontext object as defined by the EJB specification.
– The return type of the method MUST be void.
– The method MUST NOT throw a checked exception.
– The method on which PostConstruct is applied MAY be public, protected, package private or private.
– The method MUST NOT be static except for the application client.
– The method MAY be final.
– If the method throws an unchecked exception the class MUST NOT be put into service except in the case of EJBs where the EJB can handle exceptions and even recover rom them.
@Qualifier: You can use qualifiers to provide various implementations of a particular bean type. A qualifier is an annotation that you apply to a bean.
A qualifier type is a Java annotation defined as @Target({METHOD, FIELD, PARAMETER, TYPE}) and @Retention(RUNTIME).
@Interceptor: An interceptor is a class used to interpose in method invocations or lifecycle events that
occur in an associated target class. The interceptor performs tasks, such as logging or auditing, that are separate from the business logic of the application and are repeated often within an application. Such tasks are often called cross-cutting tasks.
Interceptors allow you to specify the code for these tasks in one place for easy maintenance.
When interceptors were first introduced to the Java EE platform, they were specific to enterprise beans.
On the Java EE 6 platform you can use them with Java EE managed objects of all kinds, including managed beans.
@WebService: Marks a Java class as implementing a Web Service, or a Java interface as defining a Web Service interface.
Web services are client and server applications that communicate over the World Wide Web’s (WWW) HyperText Transfer Protocol (HTTP).
As described by the World Wide Web Consortium (W3C), web services provide a standard means of interoperating between software applications
running on a variety of platforms and frameworks. Web services are characterized by their great interoperability and extensibility, as well as their machine-processable descriptions, thanks to the use of XML. Web services can be combined in a loosely coupled way to achieve complex operations.
Programs providing simple services can interact with each other to deliver sophisticated added-value services.
The webservice implementation class, is annotated as a web service endpoint using the @WebService annotation.
The class declares a single method myMethod, annotated with the @WebMethod annotation, which exposes the annotated method to web service clients.
This method returns a greeting to the client, using the name passed to it. The implementation class also must define a default, public, no-argument constructor.
@WebListener: This annotation is used to declare a WebListener. The WebListener annotation is used to register the following types of listeners:
– Context Listener (javax.servlet.ServletContextListener)
– Context Attribute Listener (javax.servlet.ServletContextAttributeListener)
– Servlet Request Listener (javax.servlet.ServletRequestListener)
– Servlet Request Attribute Listener (javax.servlet.ServletRequestAttributeListener)
– Http Session Listener (javax.servlet.http.HttpSessionListener)
– Http Session Attribute Listener (javax.servlet.http.HttpSessionAttributeListener).
@WebFault: The JAX-WS Specification demands that mapped exception MUST be annotated with a javax.xml.ws.WebFault annotation.
A wsdl:fault element is mapped to this Java exception A wsdl:fault element refers to a wsdl:message that contains a single part and is mapped to a Java bean,
called a fault bean , which is just a POJO. The exception class should have two constructors and a getter method (to obtain
fault details) – See more at: Explanation of WebFault.
@Provider: Providers are a simply a way of extending and customizing the JAX-RS runtime. You can think of them as plugins that (potentially) alter the behavior of the runtime, in order to accomplish a set of (program defined) goals.
Providers are not the same as resources classes, they exist, conceptually, at a level in-between resources classes and the JAX-RS implementation. If it helps, you can think of them in the same light as device drivers (existing between user and kernel space). This is a broad generalization. There are three classes of providers defined by the current JAX-RS specification. The commonality between them is that all providers must be identified by the @Provider annotation and follow certain rules for constructor declaration. Apart from that, different provider types may have additional annotations, and will implement different interfaces.
Entity Providers
These providers control the mapping of data representations (like XML, JSON, CSV) to their Java object equivalents.
Context Providers
These providers control the context that resources can access via @Context annotations.
Exception Providers
These providers control the mapping of Java exceptions to a JAX-RS Response instance.
@TransactionManagement: Specifies the transaction management demarcation type of the session bean or message-driven bean.
A transaction is a unit of work that changes application state—whether on disk, in memory or in a database—that, once started, is completed entirely, or not at all. Transactions can be demarcated—started, and ended with a commit or rollback—by the EJB container, by bean code, or by client code. This annotation specifies whether the EJB container or the user-written bean code manages the demarcation of a transaction.
@TransactionAttribute:Specifies whether the EJB container invokes an EJB business method within a transaction context.
WARNING: If you specify this annotation, you are also required to use the @TransactionManagement annotation
to specify container-managed transaction demarcation.
You can specify this annotation on either the bean class, or a particular method of the class that is also a method of the business interface. If specified at the bean class, the annotation applies to all applicable business interface methods of the class. If specified for a particular method, the annotation applies to that method only.
If the annotation is specified at both the class and the method level, the method value overrides if the two disagree.
If you do not specify the @TransactionAttribute annotation in your bean class, and the bean uses container managed transaction demarcation,
the semantics of the REQUIRED transaction attribute are assumed.
@Temporal: This annotation provides additional information to the persistance provider about the mapping of a java.util.Date
or java.util.Calendar property. This annotation allows you to map these object types to a date, a time, or a timestamp field in the database.
By default, the persistence provider assumes that the temporal type is a time stamp. Example: @Temporal(TemporalType.DATE).
@XmlRootElement: Define the root element for an XML tree. It’s purpose is to uniquely associate a root element with a class.
Since JAXB classes map to complex types, it is possible for a class to correspond to multiple root elements.
In this case @XmlRootElement can not be used and people start getting a bit confused.
@XmlSchema: The annotation @XmlSchema specifies the package level. To specify a package level annotation, create a class called package-info in the desired package.
@XmlType: A class maps to a XML Schema type. A class is a data container for values represented by properties and fields. A schema type is a data container for values represented by schema components within a schema type’s content model (e.g. model groups, attributes etc). To be mapped, a class must either have a public no-arg constructor or a static no-arg factory method. The static factory method can be specified in factoryMethod() and factoryClass() annotation elements. The static factory method or the no-arg constructor is used during unmarshalling to create an instance of this class. If both are present, the static factory method overrides the no-arg constructor. A class maps to either a XML Schema complex type or a XML Schema simple type. The XML Schema type is derived based on the mapping of JavaBean properties and fields contained within the class. The schema type to which the class is mapped can either be named or anonymous. A class can be mapped to an anonymous schema type by annotating the class with @XmlType(name=””).
@XmlAccessorType: Controls whether fields or Javabean properties are serialized by default. This annotation can be used with the following annotations: XmlType, XmlRootElement, XmlAccessorOrder, XmlSchema, XmlSchemaType, XmlSchemaTypes, and XmlJavaTypeAdapter.
@InterceptorBinding: Managed beans and EJB session and message-driven beans support interception. Interceptors are used to separate cross-cutting concerns from business logic.
The Java Interceptors specification defines the basic programming model and semantics. This specification defines a typesafe mechanism for associating interceptors to beans using interceptor bindings. Interceptor bindings may be used to associate interceptors with any managed bean that is not itself an interceptor or decorator or with any EJB session or message-driven bean. An interceptor instance is a dependent object of the object it intercepts.
Interceptor bindings are intermediate annotations that may be used to associate interceptors with target beans.
The interceptor bindings of an interceptor are specified by annotating the interceptor class with the binding types and the Interceptor annotation.
@Retention: Indicates how long annotations with the annotated type are to be retained. If no Retention annotation is present on an annotation type declaration, the retention policy defaults to RetentionPolicy.CLASS. A Retention meta-annotation has effect only if the meta-annotated type
is used directly for annotation. It has no effect if the meta-annotated type is used as a member type in another annotation type.
@DependsOn: Used to express an initialization dependency between singleton components. The container ensures that all singleton beans with which a singleton has a DependsOn
relationship have been initialized before the singleton’s PostConstruct method is called. During application shutdown the container ensures that all singleton beans on with which
the singleton has a DependsOn relationship are still available during the singleton’s PreDestroy method.
@Remote: Declares the remote business interface(s) for a session bean. The Remote annotation is applied to the session bean class or remote business interface
to designate a remote business interface of the bean. When used on an interface, designates that interface as a remote business interface. In this case,
no value element should be provided. The Remote annotation applies only to session beans and their interfaces.
@MappedSuperclass: Designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.
A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself.
When applied to the subclasses the inherited mappings will apply in the context of the subclass tables. Mapping information may be overridden
in such subclasses by using the AttributeOverride and AssociationOverride annotations or corresponding XML elements.
@PathParam: The @PathParam annotation is a type of parameter that you can extract for use in your resource class. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
@QueryParam: The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
@MessageLogger: Specify the project code using the projectCode attribute of the @MessageLogger annotation attached to a custom logger interface.

Java API for XML Web Services (JAX-WS) and Java API for RESTful Web Services (JAX-RS).
Web technologies include Java API for XML Web Services (JAX-WS) and Java API for RESTful Web Services (JAX-RS).

 

XML

In Java EE 6, JAX-WS provides the functionality for “big” web services. Big web services use XML messages that follow the Simple Object Access Protocol (SOAP) standard, an XML language defining a message architecture and message formats. Such systems often contain a machine-readable description of the operations offered by the service, written in the Web Services Description Language (WSDL), an XML language for defining interfaces syntactically.

See tutorial on JAXB

In Java EE 6, JAX-RS provides the functionality for Representational State Transfer (RESTful) web services. REST is well suited for basic, ad hoc integration scenarios. RESTful web services, often better integrated with HTTP than SOAP-based services are, do not require XML messages or WSDL service–API definitions. Because RESTful web services use existing well-known W3C and Internet Engineering Task Force (IETF) standards (HTTP, XML, URI, MIME) and have a lightweight infrastructure that allows services to be built with minimal tooling, developing RESTful web services is inexpensive and thus has a very low barrier for adoption. You can use a development tool such as NetBeans IDE to further reduce the complexity of developing RESTful web services.

 

A RESTful design may be appropriate when the following conditions are met:

• The web services are completely stateless. A good test is to consider whether the interaction can survive a restart of the server.
• A caching infrastructure can be leveraged for performance. If the data that the web service returns is not dynamically generated and can be cached, the caching infrastructure that web servers and other intermediaries inherently provide can be leveraged to improve performance. However, the developer must take care because such caches are limited to the HTTP GET method for most servers.
• The service producer and service consumer have a mutual understanding of the context and content being passed along. Because there is no formal way to describe the web services interface, both parties must agree out of band on the schemas that describe the data being exchanged and on ways to process it meaningfully. In the real world, most commercial applications that expose services as RESTful implementations also distribute so-called value-added toolkits that describe the interfaces to developers in popular programming languages.
• Bandwidth is particularly important and needs to be limited. REST is particularly useful for limited-profile devices, such as PDAs and mobile phones, for which the overhead of headers and additional layers of SOAP elements on the XML payload must be restricted.
• Web service delivery or aggregation into existing web sites can be enabled easily with a RESTful style. Developers can use such technologies as JAX-RS and Asynchronous JavaScript with XML (AJAX) and such toolkits as Direct Web Remoting (DWR) to consume the services in their web applications. Rather than starting from scratch, services can be exposed with XML and consumed by HTML pages without significantly refactoring the existing web site architecture.
• Existing developers will be more productive because they are adding to something they are already familiar with rather than having to start from scratch with new technology.

Container-Managed Transactions in Java EE
In an enterprise bean with container-managed transaction demarcation, the EJB container sets the boundaries of the transactions. You can use container-managed transactions with any type of enterprise bean: session, or message-driven. Container-managed transactions simplify development because the enterprise bean code does not explicitly mark the transaction’s boundaries. The code does not include statements that begin and end the transaction.

Tutorial, Container-Managed Transactions

Servlets in EE
Java Servlet technology lets you define HTTP-specific servlet classes. A servlet class extends the capabilities of servers that host applications accessed by way of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers.

SOAP as standard
Client requests and web service responses are transmitted as Simple Object Access Protocol (SOAP) messages over HTTP to enable a completely interoperable exchange between clients and web services, all running on different platforms and at various locations on the Internet.