I'm currently writing a J2EE application using Hibernate and run it on Tomcat. The project is divided into several sections (DAO, services, controllers (servlets), view(JSP)). DAOs and services are singletons. To decouple controllers and services I store references to the service interface as servlet's fields. Sonarqube tells that these fields must be marked transient, or service classes must implement Serializable, or these fields should be removed. So, is it bad to have fields in servlets? What if I just mark them transient?
It is perfectly safe to store object references in a servlet's instance fields so long as the resulting object graph is either immutable or stateless. If this is not the case then you will have concurrency problems.
Technically these fields need to have the transient
modifier applied to them because some containers will save the servlet's state during a controlled shutdown (or any other time at its convenience) using serialisation. A consequence of this is that your servlet needs to implement a private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException
method to reinstate your service reference fields.
Read the java.io.Serializable javadocs for more information.