<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> | |
<html> | |
<head> | |
<title>Getting Started with Contexts and Dependency Injection and JSF 2.x - NetBeans IDE Tutorial</title> | |
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> | |
<meta name="description" content="A demonstration of how to set up a JSF 2.0 project with CDI support in NetBeans IDE"> | |
<meta name="keywords" content="NetBeans, IDE, integrated development environment, JSF 2.0, JavaServer Faces, | |
Contexts and Dependency Injection, CDI, Web Beans"> | |
<link rel="stylesheet" type="text/css" href="../../../netbeans.css"> | |
</head> | |
<body> | |
<!-- | |
Copyright (c) 2009, 2010, 2011, Oracle and/or its affiliates. All rights reserved. | |
--> | |
<h1>Getting Started with Contexts and Dependency Injection and JSF 2.x</h1> | |
<p><em>Contributed by Andy Gibson</em></p> | |
<div class="margin-around"> | |
<div class="feedback-box margin-around float-left" style="margin-right:15px"> | |
<h3>Contexts and Dependency Injection</h3> | |
<ol> | |
<li><strong>Getting Started with CDI and JSF 2.0</strong> | |
<ul style="margin: 5px 0 0 -2em"> | |
<li><a href="#creating">Creating a Java Web Project with CDI Support</a></li> | |
<li><a href="#named">Accessing Beans from JSF's Expression Language</a></li> | |
<li><a href="#upgrading">Upgrading to an EJB</a></li> | |
<li><a href="#seealso">See Also</a></li> | |
</ul></li> | |
<li><a href="cdi-inject.html">Working with Injection and Qualifiers in CDI</a></li> | |
<li><a href="cdi-validate.html">Applying @Alternative Beans and Lifecycle Annotations</a></li> | |
<li><a href="cdi-events.html">Working with Events in CDI</a></li> | |
</ol> | |
</div> | |
</div> | |
<img src="../../../images_www/articles/73/netbeans-stamp-80-74-73.png" class="stamp" alt="Content on this page applies to NetBeans IDE 7.2, 7.3, 7.4 and 8.0" title="Content on this page applies to the NetBeans IDE 7.2, 7.3, 7.4 and 8.0" > | |
<p>Contexts and Dependency Injection (CDI), specified by <a href="http://jcp.org/en/jsr/detail?id=299">JSR-299</a>, | |
is an integral part of Java EE 6 and provides an architecture that allows Java | |
EE components such as servlets, enterprise beans, and JavaBeans to exist within | |
the lifecycle of an application with well-defined scopes. In addition, CDI | |
services allow Java EE components such as EJB session beans and JavaServer | |
Faces (JSF) managed beans to be injected and to interact in a loosely coupled | |
way by firing and observing events.</p> | |
<p>This tutorial is based on the blog post by Andy Gibson, entitled | |
<a href="http://www.andygibson.net/blog/index.php/2009/12/16/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/">Getting | |
Started with JSF 2.0 and CDI in JEE 6</a>. It demonstrates how you can use the | |
IDE to set up a Java web project with support for JSF 2.0 and CDI. It continues | |
by showing how to wire CDI managed beans with Facelets pages, and concludes with | |
a brief example of CDI integration with EJB technology.</p> | |
<p>NetBeans IDE provides built-in support for Contexts and Dependency Injection, | |
including the option of generating the <code>beans.xml</code> CDI configuration | |
file upon project creation, editor and navigation support for annotations, as | |
well as various wizards for creating commonly used CDI artifacts.</p> | |
<br style="clear:left;"> | |
<div class="indent"> | |
<p>To complete this tutorial, you need the following software and resources.</p> | |
<table> | |
<tbody> | |
<tr> | |
<th class="tblheader" scope="col">Software or Resource</th> | |
<th class="tblheader" scope="col">Version Required</th> | |
</tr> | |
<tr> | |
<td class="tbltd1"><a href="https://netbeans.org/downloads/index.html">NetBeans IDE</a></td> | |
<td class="tbltd1">7.2, 7.3, 7.4, 8.0, Java EE bundle</td> | |
</tr> | |
<tr> | |
<td class="tbltd1"><a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">Java | |
Development Kit (JDK)</a></td> | |
<td class="tbltd1">version 7 or 8</td> | |
</tr> | |
<tr> | |
<td class="tbltd1"><a href="http://glassfish.dev.java.net/">GlassFish server</a></td> | |
<td class="tbltd1">Open Source Edition 3.x or 4.x</td> | |
</tr> | |
</tbody> | |
</table> | |
<p class="notes"><strong>Notes:</strong></p> | |
</div> | |
<ul> | |
<li>The NetBeans IDE Java bundle also includes the GlassFish Server Open Source Edition, | |
which is a Java EE-compliant container.</li> | |
</ul> | |
<br> | |
<h2 id="creating">Creating a Java Web Project with CDI Support</h2> | |
<p>In this exercise you create a JSF 2.x-enabled Java web project with CDI support.</p> | |
<ol> | |
<li>Click the New Project ( <img src="../../../images_www/articles/73/javaee/cdi-intro/new-project-btn.png" | |
alt="New Project button"> ) button in the IDE's main toolbar (Ctrl-Shift-N; | |
⌘-Shift-N on Mac).</li> | |
<li>In the New Project wizard, select the Java Web category, then select Web | |
Application. Click Next.</li> | |
<li>Type <code>cdiDemo</code> for the project name and set the project location. | |
Click Next.</li> | |
<li>Set the server to GlassFish server.</li> | |
<li>Set the Java EE Version to Java EE 6 Web or Java EE 7 Web. | |
<p class="notes"><strong>Note.</strong> The Java EE version that you select | |
determines the CDI version that is enabled for your application | |
and there are some important differences between CDI 1.0 and CDI 1.1.</p> | |
<div class="indent"> | |
<ul> | |
<li>If you specify Java EE 6 Web as the Java EE version, | |
confirm that the 'Enable Contexts and Dependency Injection' option is selected. | |
The 'Enable Contexts and Dependency Injection' option, when selected, generates | |
a <code>beans.xml</code> file in the project's <code>WEB-INF</code> folder when | |
the project template is created. The <code>beans.xml</code> file is used by CDI | |
to instruct the Java EE-compliant server that the project is a module containing CDI beans. | |
Java EE 6 Web supports CDI 1.0 and the generated <code>beans.xml</code> file specifies | |
CDI 1.0 as the version.</li> | |
<li>If you specify Java EE 7 Web as the Java EE version, CDI 1.1 is enabled by default | |
and the <tt>beans.xml</tt> file is not required. In Java EE 7, when no <tt>beans.xml</tt> | |
is present the archive that is deployed is an <strong>implicit bean archive</strong>. | |
If you use the New File wizard in the IDE to manually generate a <code>beans.xml</code> file | |
in a Java EE 7 Web application, by default the deployed archive will become an | |
<strong>explicit bean archive</strong> because the <code>beans.xml</code> file | |
specifies CDI 1.1 as the version and also sets the attribute of the <tt>bean-discovery-mode</tt> to <tt>all</tt>.</li> | |
</ul> | |
<p>For more details on the types of CDI archives, see | |
<a href="http://docs.oracle.com/javaee/7/tutorial/doc/cdi-adv001.htm">Packaging CDI Applications</a> | |
in the Java EE 7 Tutorial.</p> | |
</div> | |
<img src="../../../images_www/articles/74/javaee/cdi-intro/new-web-application1.png" | |
alt="Enable CDI option provided in New Web Application wizard" | |
title="The CDI option, when selected, generates a beans.xml file for the project" | |
class="margin-around b-all"></li> | |
<li>Click Next.</li> | |
<li>In the Frameworks panel, select the JavaServer Faces option.</li> | |
<li>Click the Configuration tab and confirm that Facelets is selected as the | |
Preferred Page Language. Click Finish. | |
<p>When you click Finish, the IDE generates the web application project and opens | |
the <code>index.xhtml</code> welcome page in the editor.</p></li> | |
<li>In the Projects window, expand the Libraries > GlassFish Server node you can see that the <code>weld-osgi-bundle.jar</code> | |
library was automatically added. The GlassFish Server includes Weld, which is JBoss' implementation of the JSR-299 | |
CDI specification. | |
<br/> | |
<img src="../../../images_www/articles/73/javaee/cdi-intro/projects-window1.png" | |
alt="New project displayed in Projects window" class="margin-around b-all" | |
title="New project contains CDI's beans.xml file and the GlassFish library includes the Weld JAR file"> | |
<p>If you specified Java EE 6 Web as the Java EE version when you created the project, | |
note that the Web Pages > WEB-INF folder includes a <code>beans.xml</code> file. | |
This file is currently empty, but can be used to specify bean related information | |
in XML as an alternative to annotations.</p> | |
</li> | |
</ol> | |
<h2 id="named">Accessing Beans from JSF's Expression Language</h2> | |
<p>This exercise demonstrates how you can wire CDI managed beans to Facelets pages using | |
EL syntax.</p> | |
<ol> | |
<li>In the Projects window, right-click the Source Packages node and choose New | |
> Java Class.</li> | |
<li>In the New Java Class wizard, name the class <strong>MessageServerBean</strong>, | |
and type in <strong>exercise1</strong> as the Package. (The new package is created | |
upon completing the wizard.) Click Finish. | |
<br> | |
<img src="../../../images_www/articles/73/javaee/cdi-intro/new-java-class.png" | |
alt="New Java Class wizard" class="margin-around b-all" width="580" | |
title="Create new Java classes using the Java Class wizard"> | |
<p>The new package and class are generated, and the class opens | |
in the editor.</p></li> | |
<li>Annotate the class with the <code>@Named</code> and <code>@Dependent</code> annotations, and | |
create a single method to return a string. | |
<pre class="examplecode"> | |
package exercise1; | |
<strong>import javax.enterprise.context.Dependent; | |
import javax.inject.Named;</strong> | |
<strong>@Dependent | |
@Named</strong> | |
public class MessageServerBean { | |
<strong>public String getMessage() { | |
return "Hello World!"; | |
}</strong> | |
}</pre> | |
<p class="tips">As you type the <code>@Dependent</code> and <code>@Named</code> annotation, press | |
Ctrl-Space to invoke the editor's code completion support, as well as | |
Javadoc documentation. If you apply the annotation using the editor's | |
code completion facilities (i.e., select the appropriate annotation | |
and press Enter), the <code>import</code> statement is automatically | |
added to the file. | |
In the Javadoc pop-up, you can also click the 'Show | |
documentation in external web browser' ( | |
<img src="../../../images_www/articles/73/javaee/cdi-intro/external-web-browser-btn.png" | |
alt="Show documentation in external web browser button"> ) button | |
to display the full-sized Javadoc in a separate window.</p> | |
<p class="notes"><strong>Note.</strong> The <tt>@Dependent</tt> annotation | |
defines the scope of the managed bean. | |
In an <strong>implicit bean archive</strong> a managed bean is only discoverable | |
and can only be managed by the container when a scope is specified. | |
The application in this tutorial will be packaged as an implicit bean archive | |
if you specified Java EE 7 Web as the Java EE version when you created the project and | |
you did not create <tt>beans.xml</tt>. | |
For details on specifying the scope of managed beans, see | |
<a href="http://docs.oracle.com/javaee/7/tutorial/doc/jsf-configure001.htm">Using Annotations to Configure Managed Beans</a> | |
in the Java EE 7 Tutorial.</p> | |
</li> | |
<li>Save the file (Ctrl-S; ⌘-S on Mac). By adding the <code>@Named</code> | |
annotation, the <code>MessageServerBean</code> class becomes a <em>managed | |
bean</em>, as defined by CDI.</li> | |
<li>Switch to the <code>index.xhtml</code> Facelets page (press Ctrl-Tab) in | |
the editor, and add the following content to the <code><h:body></code> | |
tags. | |
<pre class="examplecode"> | |
<h:body> | |
Hello from Facelets | |
<strong><br/> | |
Message is: #{messageServerBean.message} | |
<br/> | |
Message Server Bean is: #{messageServerBean}</strong> | |
</h:body></pre> | |
<span class="tips">You can press Ctrl-Space in EL expressions to take | |
advantage of code completion suggestions. The editor's code completion | |
lists managed beans and their properties. Because the <code>@Named</code> | |
annotation transforms the <code>MessageServerBean</code> class into a | |
CDI managed bean, it becomes accessible within EL syntax, just as though | |
it were a JSF managed bean.</span> | |
<br> | |
<img src="../../../images_www/articles/73/javaee/cdi-intro/facelets-el-completion.png" | |
alt="New Java Class wizard" class="margin-around b-all" | |
title="Create new Java classes using the Java Class wizard"></li> | |
<li>Click the Run Project ( <img src="../../../images_www/articles/73/javaee/cdi-common/run-project-btn.png" | |
alt="Run Project button"> ) button in the IDE's main toolbar. The project | |
is compiled and deployed to GlassFish, and the application welcome page | |
(<code>index.xhtml</code>) opens in the browser. You can see the "Hello | |
World!" message from the <code>MessageServerBean</code> displayed on | |
the page. | |
<br> | |
<img src="../../../images_www/articles/73/javaee/cdi-intro/browser-output1.png" | |
alt="Welcome page displayed in browser" class="margin-around b-all" | |
title="Application welcome page displays MessageServerBean details"></li> | |
<li>Go back into the message bean and change the message to something else (e.g., | |
"Hello Weld!"). Save the file (Ctrl-S; ⌘-S on Mac), then refresh | |
the browser. The new message automatically appears. Thanks to the IDE's Deploy | |
on Save feature, any changes you save result in automatic compilation and | |
redeployment to the server. | |
<br><br> | |
From the third line in the page you can see that the class name is | |
<code>exercise1.MessageServerBean</code>. Note that the bean is just a POJO | |
(Plain Old Java Object). Even though you are developing in Java EE, there is | |
no complex class hierarchy wrapped in layers of transactions, interceptors | |
and all that "heavy" stuff you keep hearing about.</li> | |
</ol> | |
<div class="indent"> | |
<h3>What's Going On?</h3> | |
<p>When the application is deployed the server looks for CDI managed beans. | |
In a Java EE 7 application, the classes on the path are scanned for CDI annotations | |
by default. | |
In a Java EE 6 application, the classes are scanned for CDI annotations if the module contains a <code>beans.xml</code> file. | |
In a CDI module, all beans are registered with | |
Weld, and the <code>@Named</code> annotation is used to match beans to injection | |
points. When the <code>index.xhtml</code> page was rendered, JSF tried to resolve | |
the value of <code>messageServerBean</code> in the page using the registered | |
expression resolvers in JSF. One of these is the Weld EL Resolver which has the | |
<code>MessageServerBean</code> class registered under the name <code>messageServerBean</code>. | |
We could have specified a different name with the <code>@Named</code> annotation, | |
but since we did not it was registered under the default name, being the class | |
name with a lower-case first letter. The Weld resolver returns an instance of | |
this bean in response to the request from JSF. Bean naming is only needed when | |
using EL expressions and should not be used as a mechanism for injection since | |
CDI provides type-safe injection by class type and qualifier annotations.</p> | |
</div> | |
<br> | |
<h2 id="upgrading">Upgrading to an EJB</h2> | |
<p>As we are using a Java EE stack, we can easily deploy our bean as an EJB with some | |
small changes thanks to EJB 3.1.</p> | |
<ol> | |
<li>Open the <code>MessageServerBean</code> and add the <code>javax.ejb.Stateless</code> | |
annotation at the class level and change the string to 'Hello EJB!'. | |
<pre class="examplecode"> | |
package exercise1; | |
<strong>import javax.ejb.Stateless;</strong> | |
import javax.enterprise.context.Dependent; | |
import javax.inject.Named; | |
/** | |
* | |
* @author nbuser | |
*/ | |
@Dependent | |
@Named | |
<strong>@Stateless</strong> | |
public class MessageServerBean { | |
public String getMessage() { | |
return "<strong>Hello EJB!</strong>"; | |
} | |
}</pre></li> | |
<li>Save the file (Ctrl-S; ⌘-S on Mac), then go to your browser and refresh. | |
You will see output similar to the following: | |
<br> | |
<img src="../../../images_www/articles/73/javaee/cdi-intro/browser-output-ejb1.png" | |
alt="EJB details displayed in browser" class="margin-around b-all" | |
title="Using the @Stateless annotation transforms MessageServerBean into an EJB"> | |
<br> | |
Amazingly, we turned our POJO into a fully-featured EJB with just one annotation. | |
We saved changes then refreshed the page, and our changes appeared. In doing so it | |
wasn't necessary to create any weird project configurations, local interfaces or | |
arcane deployment descriptors.</li> | |
</ol> | |
<div class="indent"> | |
<h3>Different EJB types</h3> | |
<p>You can also try using the <code>@Stateful</code> annotation. Alternatively, you | |
could try the new <code>@Singleton</code> annotation for singleton instances. If | |
you do, you may notice that there is are two annotations: <code>javax.ejb.Singleton</code> | |
and <code>javax.inject.Singleton</code>. Why two singletons? The CDI singleton | |
(<code>javax.inject.Singleton</code>) lets you define a singleton instance outside | |
of EJB in case you are using CDI in a non-EJB environment. The EJB singleton | |
(<code>javax.ejb.Singleton</code>) provides all the features of an EJB such as | |
transaction management. Therefore, you have the choice depending on your needs | |
and whether you are working in an EJB environment.</p> | |
</div> | |
<div class="feedback-box"> | |
<a href="/about/contact_form.html?to=3&subject=Feedback:%20Getting%20Started%20with%20CDI%20and%20JSF%202.0">Send Feedback on This Tutorial</a> | |
</div> | |
<br style="clear:both;"> | |
<h2 id="seealso">See Also</h2> | |
<p>The next installment of this series focuses on CDI injection, and provides a | |
closer look at using CDI for managing dependencies in a Java EE environment.</p> | |
<ul> | |
<li><a href="cdi-inject.html">Working with Injection and Qualifiers in CDI</a></li> | |
</ul> | |
<p>For more information about CDI and JSF 2.0, see the following resources.</p> | |
<div class="indent"> | |
<h3>Contexts and Dependency Injection</h3> | |
<ul> | |
<li><a href="cdi-validate.html">Applying @Alternative Beans and Lifecycle Annotations</a></li> | |
<li><a href="cdi-events.html">Working with Events in CDI</a></li> | |
<li><a href="http://blogs.oracle.com/enterprisetechtips/entry/using_cdi_and_dependency_injection">Enterprise Tech Tip: Using CDI and Dependency Injection for Java in a JSF 2.0 Application</a></li> | |
<li><a href="http://docs.oracle.com/javaee/7/tutorial/doc/cdi-basic.htm">The Java EE 6 Tutorial: Introduction to Contexts and Dependency Injection for Java EE</a></li> | |
<li><a href="http://jcp.org/en/jsr/detail?id=299">JSR 299: Specification for Contexts and Dependency Injection</a></li> | |
</ul> | |
<h3>JavaServer Faces 2.0</h3> | |
<ul> | |
<li><a href="../web/jsf20-intro.html">Introduction to JavaServer Faces 2.x</a></li> | |
<li><a href="../web/jsf20-crud.html">Generating a JavaServer Faces 2.x CRUD Application from a Database</a></li> | |
<li><a href="../../samples/scrum-toys.html">Scrum Toys - The JSF 2.0 Complete Sample Application</a></li> | |
<li><a href="http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html">JavaServer Faces Technology</a> (Official homepage)</li> | |
<li><a href="http://docs.oracle.com/javaee/7/tutorial/doc/jsf-page.htm">The Java EE 7 Tutorial: Using JavaServer Faces Technology in Web Pages</a></li> | |
<li><a href="http://jcp.org/en/jsr/summary?id=314">JSR 314: Specification for JavaServer Faces 2.0</a></li> | |
</ul> | |
</div> | |
</body> | |
</html> |