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.
transient is a variables modifier used in serialization. At the time of serialization, if we don't want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type.
Transient in Java is used to mark the member variable not to be serialized when it is persisted to streams of bytes. This keyword plays an important role to meet security constraints in Java. It ignores the original value of a variable and saves the default value of that variable data type.
A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process.
A transient variable is a special type of variable which we create by using the transient keyword. It is a special type of variable which have a non-serialized value at the time of serialization. A variable that is initialized by its default value during de-serialization is known as a transient variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With