Over a million developers have joined DZone.

Injecting Guice managed object into JSF View Scoped bean

DZone's Guide to

Injecting Guice managed object into JSF View Scoped bean

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

In previous post, I demonstrate how to integrate JSF with Guice and MyBatis. However, my friend experiences some problem when he is using view scoped backing bean.
He found that he cannot re-inject the service class after serialization. I have done some tricks to solve this problem.This is simply done by overriding the readObject() and writeObject() method.

The BasePageBean in the previous post is changed as follow:


package org.borislam.view;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.servlet.ServletContext;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.ppstation.PpContext;
public abstract class BasePageBean  implements Serializable{
   private transient Injector injector;
   public BasePageBean() {}
   public Injector getInjector() {
     if(injector == null) {
       ServletContext servletContext = (ServletContext)FacesContext.getCurrentInstance().
       injector = (Injector)servletContext.getAttribute(Injector.class.getName()); 
     return injector;
   public void setInjector(Injector injector) {
     this.injector = injector;
   public void init() {
   private void writeObject(ObjectOutputStream stream) throws IOException {
      System.out.println("write object...");
   private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
      System.out.println("read object...");
   public  Flash flashScope (){
   return (FacesContext.getCurrentInstance().getExternalContext().getFlash());

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.


Published at DZone with permission of Boris Lam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}