Search code examples
servletscoding-stylejava-ee-6glassfish-3servlet-3.0

Servlets - use constructor or not?


Constructors in servlets is considered a good/bad practice ? How does it compare to the init() method ? Using servlet-3 and vanilla javaEE (CDI provided by javax.inject package)


Solution

  • There is nothing wrong in using constructors in servlets. The reason to switch to init() is when you need to obtain ServletConfig, ServletContext, etc. These objects might not be available (yet) in constructor.

    Also hypothetically some containers might do fancy things with servlets like dynamic subclassing or proxying. Finally side-effects in constructors tend to make testing harder.

    To avoid unexpected behaviour and make sure your servlets are 100% portable just stick with init(). Also if you use destroy() as well, implementing init() will make your code more "symmetric".

    See also