我正在开发一个名为 bookstore 的示例应用程序,我在其中使用了依赖注入。非常简单的应用程序。我正在使用 JavaEE 6、GlassFish 3.1.2、类中的静态数据(无 db)、Eclipse Juno。
如果需要,我可以提供更多信息。
我得到的错误:
WARNING: StandardWrapperValve[com.bookstore.web.BookListServlet]: PWC1406: Servlet.service() for servlet com.bookstore.web.BookListServlet threw exception
java.lang.NullPointerException
at com.bookstore.web.BookListServlet.doGet(BookListServlet.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
我知道这是没有注入依赖项。没有创建类实例来使用它。如果我删除 @Inject 并创建了一个类的实例,那么页面加载正常。
Servlet 代码生成错误:见粗体注释
package com.bookstore.web;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bookstore.BookRepositoryImp;
@WebServlet("/book/")
public class BookListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Inject
private BookRepositoryImp bookRepo;
public BookListServlet() {
super();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
**//bookRepo = new BookRepositoryImp(); If uncommect this code and remove @Inject than page working fine**
req.setAttribute("books", bookRepo.listBooks());
String path = "/WEB-INF/pages/book-list.jsp";
getServletContext().getRequestDispatcher(path).forward(req, res);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
}
}
项目结构: