2010-11-20

JSF: Inject FacesContext

In JSF, the standard way of accessing FacesContext is through a static call:

FacesContext context =
   FacesContext.getCurrentInstance();

Static calls defy the purpose of OO programming, make unit testing hard, and you have to create a local variable.

Now, with the dawn of JEE6 and dependency injection you would like to do just that:

@Inject
private FacesContext facesContext;

But it doesn’t work. Here is some explanation why.


The solution


The solution is to use Seam Faces. Seam Faces allow you to access FacesContext, ExternalContext and NavigationHandler without having to make static calls.

Here’s how you can add it to your project:

<dependency>
   <groupId>org.jboss.seam.faces</groupId>
   <artifactId>seam-faces</artifactId>
   <version>3.0.0.Alpha3</version>
</dependency>

And it just works! Of course your server must support CDI.


Unit testing


Obviously, the tests require a bit of clumsy boilerplate. If you find it confusing, you can read more about unit testing with Arquillian.

package me.m1key.sample.singlecall;

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import javax.inject.Inject;

import org.jboss.arquillian.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.impl.base.asset.ByteArrayAsset;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class UserBeanTest {
   @Deployment
   public static JavaArchive createTestArchive()
           throws IllegalArgumentException, IOException {
       return ShrinkWrap.create("test.jar", JavaArchive.class)
               .addManifestResource(new ByteArrayAsset(new byte[0]),
                       ArchivePaths.create("beans.xml")).addClasses(
                       UserBean.class, MockFacesContext.class);
   }

   @Inject
   private UserBean userBean;

   @Test
   public void thereShouldBeTwoUserNames() {
       assertEquals(2, userBean.getUsernames().size());
   }

}


Sample


You can download sample code (a Maven app) that works on JBoss 6 M5.

4 comments:

  1. Or instead of including a entire framework you can include the following class:

    import javax.enterprise.context.RequestScoped;
    import javax.enterprise.inject.Produces;
    import javax.faces.context.FacesContext;

    public class FacesContextProducer {

    @Produces
    @RequestScoped
    public FacesContext getContext() {
    return FacesContext.getCurrentInstance();
    }
    }

    ReplyDelete
  2. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.

    Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.

    Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

    The Nodejs Projects Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete
  3. I visited your mentioned website and thoroughly examined it. I found it really helpful according to my project requirements, but it is a little bit expensive as compared to my budget. So, I am thinking of searching for others to compare. So, I can get the best service that will Do My Dissertation For Me Uk based at an affordable price.

    ReplyDelete