vineri, 4 septembrie 2015

Injecting context (init) parameters via OmniFaces @ContextParam annotation

Starting with OmniFaces 2.2 we can inject context parameters (parameters declared in web.xml file) via @ContextParam annotation. Let's suppose that we have the below two context parameters, javax.faces.PROJECT_STAGE and dummy:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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-app_3_1.xsd">

 <context-param>
  <param-name>javax.faces.PROJECT_STAGE</param-name>
  <param-value>Development</param-value>
 </context-param>
 <context-param>
  <param-name>dummy</param-name>
  <param-value>Some.Dummy.Value</param-value>
 </context-param>
 ...
</web-app>

As a JSF page author, you can easily use these context parameters as below:

<h:outputText value="#{initParam['javax.faces.PROJECT_STAGE']}"/>
<h:outputText value="#{facesContext.externalContext.initParameterMap['javax.faces.PROJECT_STAGE']}"/>

In a "traditional" approach these context parameters are programmatically available via ExternalContext#getInitParameter():

FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
// Development
String stage = ec.getInitParameter("javax.faces.PROJECT_STAGE");
// Some.Dummy.Value
String dummy = ec.getInitParameter("dummy");

Or, you can use the OmniFaces shortcut, Faces#getInitParameter() for getting a single parameter by name, or, Faces#getInitParameterMap() for getting the application initialization parameter map.

Starting with OmniFaces 2.2 we can inject context parameters (parameters declared in web.xml file) via @ContextParam annotation, as below:

@Named
@RequestScoped
public class MyBean {

 private static final Logger LOG = Logger.getLogger(MyBean.class.getName());

 // The name can be optionally specified via the 'name' attribute, which shall more often be used as context parameters may have a.o. periods 
 // and/or hyphens in the name, which are illegal in variable names.
 @Inject
 @ContextParam(name = "javax.faces.PROJECT_STAGE")
 private String projectStage;

 // By default the name of the context parameter is taken from the name of the variable into which injection takes place.
 @Inject
 @ContextParam
 private String dummy;

 public void doSomething() {
  LOG.log(Level.INFO, "projectStage = {0}", projectStage); // Development
  LOG.log(Level.INFO, "dummy = {0}", dummy); // Some.Dummy.Value
 }
}

If you check the source code of @ContextParam (org.omnifaces.cdi.contextparam.ContextParamProducer and org.omnifaces.cdi.ContextParam) you will notice that OmniFaces gets the qualifier annotation of the given qualifier class from the given injection point via utility method, Beans#getQualifier(). This method is presented here.

Niciun comentariu:

Trimiteți un comentariu