简体   繁体   English

如何序列化和反序列化CDI Bean到文件

[英]Howto serialize and deserialize CDI Bean to file

I'm building a JSF application. 我正在构建一个JSF应用程序。 The JSF application contains some CDI beans, which hold the session data. JSF应用程序包含一些CDI bean,它们保存会话数据。 I want to save this session data to a file and load it at a later time. 我想将此会话数据保存到文件中并在以后加载。

Example 1: 范例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: 范例2:

A session scoped bean, which contains another bean, which should be loaded. 会话范围的Bean,其中包含另一个应加载的Bean。

@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? 这可能吗?

The class may be serialized or not regardless the framework you're using. 无论您使用的是哪种框架,该类都可以序列化或不序列化。 CDI and JSF are irrelevant for your problem. CDI和JSF与您的问题无关。 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. 只要确保您的类及其所有字段都可以序列化/反序列化即可,如果您有一个不能序列化的字段,则将其标记为transient并通过实现readObject方法建立规则以在对象反序列化上创建它。

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). 注意:有些应用程序服务器可以为您启用此选项:将会话数据存储在磁盘中的文件中,以便在应用程序重新部署后像JBoss一样加载(在JBoss AS 7中测试了此行为)。 There's no need to reinvent the wheel. 无需重新发明轮子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM