简体   繁体   中英

Can we create a non parameterized constructor in servlet?

What I know till now:

  • Instance of Servlet is first created by container via reflection and no argument constructor gets used.
  • Then parameterized init method gets called.

Also it is suggested that we should not create a constructor in servlet class as it is of no use. And I agree with that.

Lets say, I have created a no argument constructor in servlet class and from within that I am calling a parameterized constructor. My question is, will it be called by the container?

public class DemoServlet extends HttpServlet{  
   public DemoServlet() {
      this(1);
   }
   public DemoServlet(int someParam) {
      //Do something with parameter
   }
}

Will DemoServlet() be called by the container and if we put some initializing stuff inside it, it will be executed? My guess is yes but it's just a guess based on my understanding.

This might be pretty useless, I am asking out of curiosity.

DemoServlet() will be called (as you are overriding the defined no-arg constructor in HttpServlet (which is a no-op constructor).

However the other DemoServlet(int arg) will not be called.

You are correct with your guess. DemoServlet() would be called by the container and any initialization code within it would be executed - even if that initialization is done through constructor-chaining And as a matter of fact this is a good way to have dependency injection and create a thread-safe servlet which is testable Typically it would be written this way

public class DemoServlet extends HttpServlet
{
   private final someParam; //someParam is final once set cannot be changed

   //default constructor called by the runtime.
   public DemoServlet()
   {
       //constructor-chained to the paramaterized constructor
       this(1);
   }

   //observe carefully that this paramaterized constructor has only
  //package-level visibility. This is useful for being invoked through your
  //  unit and functional tests which would typically reside within the same 
  //package. Would also allow your test code to inject required values to 
 //verify behavior while testing.
   DemoServlet(int someParam)
   {
      this.param = param
   }

   //... Other class code...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM