java - Can we create a non parameterized constructor in servlet? -
what know till now:
- instance of servlet first created container via reflection ,
no argument constructorgets used. - then
parameterized initmethod gets called.
also suggested should not create constructor in servlet class of no use. , agree that.
lets say, have created no argument constructor in servlet class , within calling parameterized constructor. question is, called container?
public class demoservlet extends httpservlet{ public demoservlet() { this(1); } public demoservlet(int someparam) { //do parameter } } will demoservlet() called container , if put initializing stuff inside it, executed? guess yes it's guess based on understanding.
this might pretty useless, asking out of curiosity.
you correct guess. demoservlet() called container , initialization code within executed - if initialization done through constructor-chaining , matter of fact way have dependency injection , create thread-safe servlet testable typically written way
public class demoservlet extends httpservlet { private final someparam; //someparam final once set cannot changed //default constructor called runtime. public demoservlet() { //constructor-chained paramaterized constructor this(1); } //observe paramaterized constructor has //package-level visibility. useful being invoked through // unit , functional tests typically reside within same //package. allow test code inject required values //verify behavior while testing. demoservlet(int someparam) { this.param = param } //... other class code... }
Comments
Post a Comment