[英]Can we create a non parameterized constructor in servlet?
What I know till now: 我到目前为止所知道的:
no argument constructor
gets used. no argument constructor
使用no argument constructor
。 parameterized init
method gets called. parameterized init
方法。 Also it is suggested that we should not create a constructor in servlet class as it is of no use. 另外建议不要在servlet类中创建构造函数,因为它没有用。 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. 可以说,我在servlet类中创建了一个无参数构造函数,并从中调用了参数化构造函数。 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? 容器将调用
DemoServlet()
,如果在其中放入一些初始化的东西,它将被执行? 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). DemoServlet()
将被调用(因为您将重写HttpServlet中定义的no-arg构造函数(这是一个no-op构造函数))。
However the other DemoServlet(int arg)
will not be called. 但是,另一个
DemoServlet(int arg)
将不会被调用。
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
容器将调用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...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.