Should I declare injected variables as transient in Java EE?
Asked Answered
M

2

8

Should I declare injected variables as transient in Java EE?

I am getting a FindBugs warning:

Class com.playaround.HelloServlet defines non-transient non-serializable instance field accelerationUnit
This Serializable class defines a non-primitive instance field which is neither transient, Serializable, or java.lang.Object, and does not appear to implement the Externalizable interface or the readObject() and writeObject() methods.
Objects of this class will not be deserialized correctly if a non-Serializable object is stored in this field.

The code in play is:

/**
 * Sample of a web service reference.
 */
@WebServiceRef
private AccelerationUnit accelerationUnit;

Same question applies to @Resource, @Inject, @PersistenceUnit etc.

Macey answered 23/9, 2013 at 14:48 Comment(0)
C
7

It depends ;) With @Inject and other CDI annotations you should check chapter 6.6 of JSR-299 specification. You have got there information which beans are "passivation capable".

About stateless and singleton session beans, according to EJB specification, they cannot be serialized (as ejb passivation doesn't occur)

Last think and most problematic is stateful session beans. All JavaEE resources (EJB, InitialContext, SessionContext etc) will be restored after activation, but you have to take care of other non-serializable fields and open connections. So in your case IMHO you should mark accelerationUnit as transient and restore in ejbActivate event, or involve CDI and producer methods to inject field automagically.

Chere answered 23/9, 2013 at 22:5 Comment(1)
I should re-edit the question to limit it to AT WebServiceRef only since that was what I was working on. However, I did notice I have the same issue if I inject a AT PersistenceUnit and AT EJB in a servlet so I thought it can be expanded.Macey
S
-3

In the definition of the class AccelerationUnit, make it like:

class AccelerationUnit implements Serializable{
    // your code here
  }
Stulin answered 23/9, 2013 at 15:32 Comment(1)
AccelerationUnit is a webserviceclient not a serializable class. It was given as an example.Macey

© 2022 - 2024 — McMap. All rights reserved.