使用CDI(Weld),我为非序列化类实现了一个生成器方法。如果生产者被序列化并且字段 NonSerializableObject 消失了,我重新初始化NonSerializableObject:
@SessionScoped
public class NonSerializableObjectProducer implements Serializable {
/** UUID */
private static final long serialVersionUID = -436472364723647647367L;
/** my transient non serializbale object */
private transient NonSerializableObject nonSerializableObject;
@SessionScoped
@Produces
protected NonSerializableObject produceNonSerializableObject() {
if (nonSerializableObject == null) {
// reinitialize object and set it
// nonSerializableObject = ...
}
return nonSerializableObject;
}
我注入一个NonSerializableObject,如:
@SessionScoped
public class UseSerializableObject implements Serializable {
private static final long serialVersionUID = 62378785678643784689L;
@Inject
private transient NonSerializableObject nonSerializableObject;
public void doSomething() {
nonSerializableObject.go();
}
}
当我的应用程序服务器(Tomcat 7)重新部署时,会发生以下异常:
Sep 22, 2014 4:41:58 PM org.apache.catalina.session.StandardSession writeObject
WARNING: Cannot serialize session attribute WELD_S#5 for session 4694BB90FF1BBD8
java.io.NotSerializableException: com.MemberOfNonSerializableObject
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1181)
因此,我的NonSerializableObject的成员变量被序列化。为什么?我宣称一切都是短暂的!
答案 0 :(得分:3)
你的方法:
@SessionScoped
@Produces
protected NonSerializableObject produceNonSerializableObject() {}
生成@SessionScoped
对象,该对象不可序列化。所有@RequestScoped,@ SessionScoped和@ApplicationScoped bean必须是Serializable。
如果你从生产者方法中删除@SessionScoped,它会起作用。