如何运用spring将dao注入到servlet中?

1.servlet的init方法

public void init(ServletConfig config) throws ServletException {
     super.init(config); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(
this,
         config.getServletContext());
}

2.为servlet添加私有字段,利用@Autowired自动注入

@Autowired
private Dao dao;

 3.注意事项,super.init(config);如果不加,之后在servlet中获取ServletContext对象的时候会抛空指针异常,因为我们重写了init(ServletConfig),而父类中的init(ServletConfig)有处理获取ServletContext对象的引用。

所以得注意了,要加上super.init(config);

原文地址:https://www.cnblogs.com/zyh1994/p/5871337.html