Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

6 Reasons Why You Should Try Cdi 1.2

DZone's Guide to

6 Reasons Why You Should Try Cdi 1.2

If you have not tried moving to CDI 1.2 from CDI 1.0 on Liberty, please consider trying it. Here are some of the cool new functionalities in CDI 1.2…

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

I intended to write this article when Liberty 8.5.5.6 was released in June last year. Liberty 8.5.5.6 provided the cdi-1.2 feature together with other Java EE 7 features such as servlet-3.1, jsf-2.2, etc. The CDI 1.2 feature was based on Weld, while the CDI 1.0 feature had used OpenWebBeans.

If you have not tried moving to CDI 1.2 from CDI 1.0 on Liberty, please consider trying it. Here are some of the cool new functionalities in CDI 1.2…

1) Global Enablement of Interceptors, Decorators, and Alternatives

In CDI 1.2, the interceptors, decorators, and alternatives can by enabled globally using @Priority:

@Priority(1100)
@Interceptor
public class MyInterceptor{
}

Read Ashley’s article to learn more about the interceptors and how to enable the interceptors globally.

In CDI 1.0, it was necessary to enable the interceptors using the following XML but the enablement applied only to the containing archive:

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
       http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd">
      <interceptors>
        <class>com.acme.MyInterceptor</class>
 </ interceptors>
</beans>

In CDI 1.2, in addition to global enablement, the interceptors can be bound to constructors.

2) Automatic Enablement of CDI for Beans

Any classes with bean-defining annotations or session beans will be discovered as CDI beans without the presence of beans.xml. If you want to disable this (and improve startup time), place the following entry in the server.xml:

<cdi12 enableImplicitBeanArchive=”false”/>

3) Easily Prevent Scanning of Classes and Packages

You can use class exclusion filters in beans.xml to prevent scanning of classes and packages:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee">
 <scan>
  <exclude name="com.acme.rest.*" />
   <exclude name="com.acme.faces.**">
    <if-class-not-available name="com.acme.MyBean"/>
   </exclude>
   <exclude name="com.acme.verbose.*">
    <if-system-property name="verbosity" value="low"/>
    </exclude>
   <exclude name="com.acme.ejb.**">
    <if-class-available name="javax.enterprise.inject.Model"/>
     <if-system-property name="exclude-ejbs"/>
   </exclude>
 </scan>
</beans>
  • The first exclude filter (line 4) excludes all classes in the com.acme.rest package.
  • The second exclude filter (line 5) includes all classes in the com.acme.faces packages, and any subpackages, but only if com.acme.MyBean is not available.
  • The third exclude filter (line 8) excludes all classes in the com.acme.verbose package if the system property verbosity has the value of low.
  • The final exclude filter (line 10) excludes the classes in the com.acme.ejb packages, and any subpackages, if the system property exclude-ejbs is set.

4) Allow Programmatic Disabling of Classes

Use the @Vetoed annotation to allow easy programmatic disabling of classes or packages. The following snippet is to veto the class MyBean from being treated as a CDI bean:

@Vetoed
public class MyBean{
...
}

If all classes under a package need to be excluded from CDI scanning, you should put @Vetoed on the package level. The following snippet prevents all classes under the package com.acme.util from being considered CDI beans:

@Vetoed
package com.acme.util

5) Great Integration With Other Java EE Components!

As mentioned in the Java EE 7 specification, the following components support CDI injections, including constructor injection and the use of interceptors. You can freely use injection on the following component classes:

Component Classes supporting injection
Servlet servlets, servlet filters, event listeners
JSP tag handlers, tag library event listeners
JSF managed classes
JAX-WS service endpoints, handlers
JAX-RS JAX-RS components
WebSocket endpoints
EJB beans
Interceptor interceptors
Java Persistence entity listeners
Managed Beans managed beans
CDI CDI-style managed beans, decorators
Java EE platform main class (static), login callback handler

Below is an example of a Servlet class supporting the constructor injection:

@WebServlet(urlPatterns = { "/CDIConstructorInjection" })
public class CDIConstructorInjectServlet extends HttpServlet {
 /** Standard serialization ID. */
 private static final long serialVersionUID = 1L;
  /** Storage for the injected constructor bean. */
  private final CDIDataBean constructorBean;
  /**
   * Constructor injection: When this servlet is instantiated,
   * inject a bean as a parameter to the servlet constructor.
   * @param cb The constructor bean which is to be set.
   */
  @Inject
  public CDIConstructorInjectServlet(ConstructorBean cb) {
   this.constructorBean = cb;
  }
  /**
   * Post-construct injection: Invoked via injection 
   * following the construction of this servlet instance.
   */
   @PostConstruct
   void start() {
    System.out.println("Post construct is called");
   }
  /**
   * Pre-destroy: Invoked via injection preceding the  
   * destruction of this servlet instance.
   */
  @PreDestroy
  void stop() {
   System.out.println("PreDestroy is called");
  }

  @Override
  protected void doGet(HttpServletRequest request,
   HttpServletResponse response) 
   throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    writer.print(constructorBean.toString());            
  }
}

6) A Number of Java EE Components Provide CDI Extensions

When using the cdi-1.2 feature together with other Java EE 7 features, such as Transaction, BeanValidation, JMS, JBatch and JSF, you will get some additional CDI extensions provided by these features, detailed below:

  • Transaction CDI extension: provides the @Transactional interceptor and a new CDI scope TransactionScoped
  • Bean Validation feature: provides the Validator and ValidatorFactory beans and BValBinding interceptor
  • JMS feature: provides the JMSContext bean
  • JBatch feature: provides the beans JobContext, StepContext, and the annotation BatchProperty
  • JSF feature: provides the new CDI scopes such as ViewScoped, FlowScoped, and the FlowDefinition annotation

Using the CDI 1.2 feature is easy. Just specify the following entries in the server.xml (the example configures the server to use the CDI 1.2, Servlet 3.1, and JSF 2.2 features):

<featureManager>
        <feature>cdi-1.2</feature>
        <feature>servlet-3.1</feature>
        <feature>jsf-2.2</feature>
</featureManager>

Have fun!

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
java ee ,java ,extensions ,beans ,constructor ,cdi ,injection ,bean

Published at DZone with permission of Emily Jiang, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}