[英]Can we create a non parameterized constructor in servlet?
我到目前為止所知道的:
no argument constructor
使用no argument constructor
。 parameterized init
方法。 另外建議不要在servlet類中創建構造函數,因為它沒有用。 我同意這一點。
可以說,我在servlet類中創建了一個無參數構造函數,並從中調用了參數化構造函數。 我的問題是,容器會調用它嗎?
public class DemoServlet extends HttpServlet{
public DemoServlet() {
this(1);
}
public DemoServlet(int someParam) {
//Do something with parameter
}
}
容器將調用DemoServlet()
,如果在其中放入一些初始化的東西,它將被執行? 我的猜測是肯定的,但這只是基於我的理解而得出的猜測。
我出於好奇而問,這可能毫無用處。
DemoServlet()
將被調用(因為您將重寫HttpServlet中定義的no-arg構造函數(這是一個no-op構造函數))。
但是,另一個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...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.