Search This Blog

Wednesday, September 21, 2016

CDI Best Practices with Real-Life Examples [TUT3287] @JavaOne16

CDI Best Practices with Real-Life Examples [TUT3287]



Session ID: TUT3287
Session Title / Download Link : CDI Best Practices with Real-Life Examples [TUT3287]
Session Type: Tutorial Session
Session Abstract:
As the adoption of Contexts and Dependency Injection (CDI) for Java EE API grows, it is important to understand how to use CDI effectively to maximize the benefits of using a loosely coupled, type-safe, annotation-driven dependency injection solution. This session outlines the best practices for using CDI, such as annotations versus XML, @Named as a qualifier, qualifier type safety versus verbosity, effective use of producers/disposers, using scopes properly, best practices for using conversations, defining effective stereotypes, interceptors versus decorators, static versus dynamic injection/lookup, CDI versus Java EE resource injection, using CDI with EJB 3.1, CDI/JSF 2 integration patterns, and CDI/JPA 2 usage patterns.


Friday, September 16, 2016

Create First CDI Application

1- Create new Netbeans Project named "CDI_JavaOne16_TUT3287_Demo"

2- Edit the "Web.xml"

<servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

and 

<welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
</welcome-file-list>


3- Run the project
Is it works OK

4- Start our coding

5- create a POJO Bean named "HelloWorld"
5.1 - add method
    public String sayHello(){
        return "Hello User from CDI !";
    }


6- create Managed bean for the page named "HelloManagedBean" with request scope
import javax.enterprise.context.RequestScoped;
6.1 - Inject the bean
    @Inject
    private HelloWorld helloWorld;

6.1 - add action method
    public String sayHelloAction() {
        System.out.println("com.javaone.cdi.secOne.hello.beans.HelloManagedBean.sayHelloAction() : " + helloWorld.sayHello());
        return null;
    }


7- craete page named "HelloPage.xhtml"
7.1 - Add <h:form>
7.2 - add command button <h:commandButton value="Say Hello" action="#{helloManagedBean.sayHelloAction}"/>


8- Activate CDI by adding the beans.xml
8.1 - update the configuration to be  bean-discovery-mode to be "all"
<?xml version="1.0" encoding="UTF-8"?>
<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"
       bean-discovery-mode="all">
</beans>


9- Run