//enterprise java /
Convention over Configuration
in Java EE 6
COMMUNITY
ADAM BIEN
Learn to specify the unconventional through Convention
over Configuration.
JAVA IN ACTION
Convention over Configuration in Java EE 6 requires you to
specify only the unconventional.
Obvious choices do not have to be
configured. However, some of the
environmental or deployment-dependent choices simply cannot
be derived from the convention
and have to be configured. This
article focuses on project-specific
or product-specific configuration of Java EE 6 applications that
require explicit configuration.
A Stage can be represented as
an enum and injected to all interested resources:
public enum Stage {
Development, Unit Test,
System Test, Production
}
PHOTOGRAPH BY
THOMAS EINBERGER/
GETTY IMAGES
Staging
Information about the current
stage (such as test, integration, or
production) is particularly interesting for applications with high
amounts of legacy code. Legacy
connectors often are not fully
Java EE–compliant and cannot
use Java EE resource management. Instead of relying on the
application server’s configuration
capabilities, you have to mock out
external resources in the prepro-duction stages.
The current stage can be
explicitly configured as a system property, configuration file,
database, or any resource you
prefer. JavaServer Faces 2 (JSF 2)
supports a configurable staging
environment with the ProjectStage
class, so we can expose the existing information with a managed
bean (see Listing 1).
The ProjectStage class originates
from the JSF 2 API and belongs to
the UI layer. To decouple the business logic implementation from
the UI, the FacesContextExposer
managed bean (Listing 1) converts the ProjectStage into a neutral Stage enum. The method
FacesContextExposer#stage()
“produces” the Stage
and makes it available
for injection. The staging value can be configured in the JNDI tree
with the key java:comp/
env/jsf/ProjectStage or
with the context-param
tag in the web.xml
deployment descrip-tor (see Listing 2). The
JNDI key takes precedence—it overwrites
the staging value configured in web.xml.
With the built-in
annotation @Produces exposed,
the Stage enum is directly injected
as a Stage projectStage parameter
of the ConnectorManager#connect
method (see Listing 3).
Inside the connect method,
the Stage enum is used to decide
which EISConnector implementation to create. Only in the
case of
Stage.Production is the
LegacyConnector created. For all
other stages, EISMock is instantiated and returned. To
distinguish a staged
injection from the
“usual” injection, the
connect method is
annotated with the
Convention over
Configuration
in Java EE 6
requires you to
specify only the
unconventional.
Obvious choices
do not have to be
configured.
ABOUT US
blog
59
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////////// MAY/JUNE 2012