Outcome: Get an idea of how bean works, but still don’t know how to actually use it in my own project.
Knowledge base:
Dependency Injection (DI)
refers to the process of supplying an external dependency to a software component. DI can help make your code architecturally pure.
- It aids in design by interface as well as test-driven development by providing a consistent way to inject dependencies.
For example, instead of an object looking up other objects that it needs to get its job done (dependencies), a DI container injects those dependent objects. This is the so-called Hollywood Principal.
CDI (contexts and dependency injection):
“a Java EE 6 feature that help to knit together the web tier and the transactional tier of the Java EE platform.”
A set of services that, used together, make it easy for developers to use enterprise beans along with (JSF) Java Server Faces technology in web applications.
Beans:
In CDI, a bean is a source of contextual objects that define application state and/or logic.
- A Java EE component is a bean if the lifecycle of its instances may be managed by the container according to the lifecycle context model defined in the CDI specification.
The original tutorial can be found here
What’s in this quickstart: how to create and deploy a simple application to JBoss WildFly
Information is displayed using JSF (Java Server Face view), business logic is encapsulated in two CDI beans
In depth:
The Numberguess project is comprised of the following and are packaged as a war module
- A number of beans
- Configuration files
- Facelets (JSF) views
src/main/webapp
- /WEB_INF/
faces-config.xml
: the configuration consists of only root element. WildFly automatically configure JSF if we include this file - /WEB_INF/
beans.xml
: tells WildFly to look for beans in this application and to activate the CDI
<faces-config version="2.2"
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/web-facesconfig_2_2.xsd">
</faces-config>
Notice: no web.xml is needed!
home.xhtml
: bind an action method on the bean so that the user can send their guess to the server
src/main/java/…/quickstart/numberguess
- A qualifier is used to disambiguate between two beans both of which are eligible for injection based on their type.
Generator.java
class
- application scoped, so we don’t get a different random each time.
- Creates the random number and exposes the maximum number via producer method (@Produces, @Random && @Produces, @MaxNumber)
Game.java
class is session-scoped:
- @Named annotation is only required when we want to make the bean accessible to a JSF view via EL
- The post-construct lifecycle method to initialize the game by retrieving a random number from the @RandomInstance< Integer > bean