我们可以在 servlet 中创建一个非参数化的构造函数吗?

Can we create a non parameterized constructor in servlet?

我目前所知道的:

另外建议我们不要在servlet中创建构造函数class,因为它没有用。我同意这一点。

比方说,我在 servlet class 中创建了一个无参数构造函数,并从中调用了一个参数化构造函数。我的问题是,它会被容器调用吗?

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

DemoServlet() 会被容器调用吗?如果我们在里面放一些初始化的东西,它会被执行吗?我的猜测是肯定的,但这只是基于我的理解的猜测。

这可能没什么用,我是出于好奇才问的。

DemoServlet() 将被调用(因为您正在覆盖 HttpServlet 中定义的无参数构造函数(这是一个无操作构造函数)。

但是另一个DemoServlet(int arg)不会被调用。

你猜对了。 DemoServlet() 将由容器调用,并且其中的任何初始化代码将被执行——即使该初始化是通过构造函数链完成的事实上,这是进行依赖注入和创建线程安全的好方法可测试的servlet 通常会这样写

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...
}