Spring项目servlet中用@Autowired导入的service一直是null
·
原因:servlet被tomcat容器管理,并不由spring容器管理,因此无法注入。
解决:在servlet中手动触发Spring的自动装配机制
1、检查web.xml中是否配置了spring监听器
配置监听器是为了在 Web 容器启动时 初始化 Spring 的 ApplicationContext,并将其作为整个 Web 应用的上下文环境,使 Spring 能够管理 Bean 的生命周期。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>
2、在servlet中重写init()方法启用Spring自动装配
重写的那句代码的作用是查找当前 Servlet 运行的 Spring 应用上下文。根据上下文中的 Bean 定义,把 @Autowired、@Resource 等注解的依赖注入到 Servlet 实例中。
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
@Autowired
public UserService userService;
@Override
public void init() throws ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
。。。。。
}
}
因此如果 没有 配置ContextLoaderListener,那么 Spring 不会自动创建 ApplicationContext,SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this) 也就找不到可用的 Spring 容器,无法完成自动注入。
更多推荐




所有评论(0)