1 @WebServlet("/cdiservlet") //url映射 2 public class NewServlet extends HttpServlet { 3 private Message message; 4 5 @Override //重写doGet方法 6 public void init() { 7 message = new MessageB(); //对message初始化 8 } 9 10 @Override 11 public void doGet(HttpServletRequest request, HttpServletResponse response) 12 throws IOException { //抛出可能出现IO异常 13 response.getWriter().write(message.get()); //捕获可能发生的异常 14 } 15 } 16 17 public interface Message { //servlet实现Message接口的一个对象实例 18 public String get(); 19 } 20 public class MessageB implements Message { //servlet创建以下对象的实例 21 public MessageB() { } 22 23 @Override 24 public String get() { 25 return "message B"; 26 } 27 } 28 @WebServlet("/cdiservlet") //使用CDI,servlet声明它对Message实例的依赖性,并让它由CDI运行时自动注入 29 public class NewServlet extends HttpServlet { 30 @Inject private Message message; 31 32 @Override 33 public void doGet(HttpServletRequest request, HttpServletResponse response) 34 throws IOException { //抛出可能出现IO异常 35 response.getWriter().write(message.get()); //捕获可能发生的异常 36 } 37 }