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)
Constructors in servlets is considered a good/bad practice ? How does it compare to
Share
There is nothing wrong in using constructors in servlets. The reason to switch to
init()is when you need to obtainServletConfig,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 usedestroy()as well, implementinginit()will make your code more “symmetric“.See also