The purpose of the exercise is to experiment with CDI and understand how it works.
Set Up
Create a new "Web Application" project named "Week7" that uses the "JavaServer Faces" framework. After creating the project, don't forget to add a reference to the Java EE 7 API Library (by right clicking on Libraries in the created project)!
In the project, create a Java class named "UniqueIdGenerator" in the package "au.edu.uts.aip.cdi".
Enter the following source code:
package au.edu.uts.aip.cdi;
public class UniqueIdGenerator {
private static int counter = 0;
public static synchronized int generate() {
counter++;
return counter;
}
}
Next, create three Java classes, named "MyApplicationBean", "MyRequestBean" and "MyDependentBean", also in the same package:
MyApplicationBean:
package au.edu.uts.aip.cdi;
import javax.enterprise.context.*;
import javax.inject.*;
@Named
@ApplicationScoped
public class MyApplicationBean {
private int uniqueId = UniqueIdGenerator.generate();
public int getUniqueId() {
return uniqueId;
}
}
MyRequestBean:
package au.edu.uts.aip.cdi;
import javax.enterprise.context.*;
import javax.inject.*;
@Named
@RequestScoped
public class MyRequestBean {
private int uniqueId = UniqueIdGenerator.generate();
public int getUniqueId() {
return uniqueId;
}
}
MyDependentBean:
package au.edu.uts.aip.cdi;
import javax.enterprise.context.*;
import javax.inject.*;
@Named
@Dependent
public class MyDependentBean {
private int uniqueId = UniqueIdGenerator.generate();
public int getUniqueId() {
return uniqueId;
}
}
Finally, create a JSF Page named "cdi" (i.e., cdi.xhtml) with the following contents:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>CDI Testing</title>
</h:head>
<h:body>
<p>myApplicationBean has id: #{myApplicationBean.uniqueId}.</p>
<p>myApplicationBean has id: #{myApplicationBean.uniqueId}.</p>
<p>myRequestBean has id: #{myRequestBean.uniqueId}.</p>
<p>myRequestBean has id: #{myRequestBean.uniqueId}.</p>
<p>myDependentBean has id: #{myDependentBean.uniqueId}.</p>
<p>myDependentBean has id: #{myDependentBean.uniqueId}.</p>
</h:body>
</html>
Run cdi.xhtml and look at the output.
Reflect
What does UniqueIdGenerator do?
What can we infer from the output of cdi.xhtml? What happens if you refresh the page? What does this tell us?