这是我的Servlet
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Inject IUserBusiness userBusiness;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
List<UserBean> usersList=new ArrayList<UserBean>();
usersList=userBusiness.getAllUsers();
usersList.size();
}
我有下一个界面和实现
public interface IUserBusiness {
List<UserBean> getAllUsers();
}
public class UserBusiness implements IUserBusiness{
public List<UserBean>userList;
public UserBusiness() {
userList=new ArrayList<UserBean>();
}
public List<UserBean> getAllUsers(){
UserBean user=new UserBean();
user.setAge(44);
user.setEmail("fgdfg");
user.setPassword("dfgdfgf");
userList.add(user);
return this.userList;
}
}
然后我像这样配置注入器
public class Listener扩展了GuiceServletContextListener {
@Override
protected com.google.inject.Injector getInjector() {
return Guice.createInjector(
new ServletModule() {
@Override protected void configureServlets() {
serve("/index.html").with(UserServlet.class);
}
},
new Configure());
}
和
public class Configure extends com.google.inject.AbstractModule{
@Override
protected void configure() {
bind(IUserBusiness.class).to(UserBusiness.class);
}
}
但是我收到500错误(servlet中userBusiness的nullPointer异常)
Servlet.service() for servlet [dynamic.UserServlet] in context with path [/dynamic] threw exception
java.lang.NullPointerException
at dynamic.UserServlet.doGet(UserServlet.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
答案 0 :(得分:1)
如果您正在使用Guice,为什么要设置@WebServlet("/UserServlet")
?额外的注释不会造成任何伤害,除非它可能会掩盖单独的错误配置。
确保您通过Guice绑定访问servlet,因为如果您通过其他配置访问它,则不会设置@Inject字段,并且在尝试访问它们时会获得NPE。 / p>