1. 程式人生 > >剖析servlet injection及源碼分析.

剖析servlet injection及源碼分析.

ext Language except 源碼 write get 初始 urn 依賴

@WebServlet("/cdiservlet")      
public class NewServlet extends HttpServlet {
    private Message message;

    @Override             ||重寫doGet方法
    public void init() {
        message = new MessageB();    ||對message初始化
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws IOException {              ||拋出可能出現IO異常
        response.getWriter().write(message.get());   ||捕獲可能發生的異常
    }
}

public interface Message {         ||servlet實現Message接口的一個對象實例
    public String get();
}
public class MessageB implements Message {          ||servlet創建以下對象的實例
    public MessageB() { }

    @Override
    public String get() {
        return "message B";
    }
}
@WebServlet("/cdiservlet")              ||使用CDI,servlet聲明它對Message
實例的依賴性,並讓它由CDI運行時自動註入 public class NewServlet extends HttpServlet { @Inject private Message message; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
||拋出可能出現IO異常
          response.getWriter().write(message.get());  ||捕獲可能發生的異常
}
}

剖析servlet injection及源碼分析.