- 问题描述
今天发现无法在tomcat
原生的servlet
中使用spring
容器管理的bean
,调用service
层时总是报NullPointerException
异常 - 解决方法
@WebServlet(name = "ServletTestDI", urlPatterns = "/tmptable")
public class ServletTestDI extends HttpServlet {
@Autowired
private ITmpTableService iTmpTableService;
// 这一步是解决问题的主要代码
@Override
public void init(ServletConfig config) throws ServletException {
// 将servlet容器上下文注入到spring容器中,这个类不能作用与@Resource注解
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String age = request.getParameter("age");
TmpTable tmpTable = new TmpTable(name, Integer.parseInt(age));
iTmpTableService.insTmpTable(tmpTable);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}