0

I'm building a JSF application. The JSF application contains some CDI beans, which hold the session data. I want to save this session data to a file and load it at a later time.

Example 1:

@SessionScoped
MyBean implements Serializable {

    private String myValue;

    //getter and setters
}


@RequestScoped
MyLoadingService {

    @Inject
    private MyBean myBean;

    public void load(byte[] data){
        MyBean newMyBean = (MyBean)org.apache.commons.lang3.SerializationUtils.deserialize(data);

        //this doesn't work, because myBean is a proxy here...
        //how can I achieve this to work?
        myBean = newMyBean;
    }
}

Example 2:

A session scoped bean, which contains another bean, which should be loaded.

@SessionScoped
AnotherBean implements Serializable {

    private String otherValue;

    //getter and setters
}



@SessionScoped
MyBean implements Serializable {

    @Inject
    AnotherBean anotherBean;

    private String myValue;

    //getter and setters
}


@RequestScoped
MyLoadingService {

    @Inject
    private MyBean myBean;

    public void load(byte[] data){
        MyBean newMyBean = (MyBean)org.apache.commons.lang3.SerializationUtils.deserialize(data);

        //this doesn't work, because myBean is a proxy here...
        //how can I achieve this to work?
        myBean = newMyBean;
    }
}

Is this possible?

M.R.
  • 1,959
  • 4
  • 24
  • 32

1 Answers1

0

The class may be serialized or not regardless the framework you're using. CDI and JSF are irrelevant for your problem. Just make sure that your class and all its fields can be serialized/deserialized, if you have a field that cannot be serialized, then mark it as transient and establish rules to create it on object deserialization by implementing the readObject method.

Note: there are application servers that enable this option for you: store the session data in a file in disk to load it later after application redeploy like JBoss (I tested this behavior in JBoss AS 7). There's no need to reinvent the wheel.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • It is not a question if the object can be serialized, but how can I deserialize a bean and still have CDI work. Or if this is even possible. CDI itself manages the lifecycle of the bean, I do not know, if it is possible to override a bean, which has already been managed by CDI, without breaking the lifecycle management. – M.R. Jun 24 '14 at 07:04
  • Try this: `Session session = /* fancy code to get the session */; session.setAttribute("", );`. – Luiggi Mendoza Jun 24 '14 at 07:06
  • By the way, you never posted your real problem in the question. That's why my answer is about Java object serialization. – Luiggi Mendoza Jun 24 '14 at 07:06