gpt4 book ai didi

java - Spring MVC : autowire ignored in servlets

转载 作者:行者123 更新时间:2023-11-29 07:47:41 25 4
gpt4 key购买 nike

出于某些原因,我可以在我的 Controller 中 Autowiring ,但不能在我创建的 servlet 中 Autowiring 。

这是我的 servlet 的顶部:

@Component
public class MyServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

@Autowired
private CobiService cobiService;

在我的 web.xml 中,这是相关配置:

    <servlet>
<servlet-name>convservlet</servlet-name>
<servlet-class>com.gim.servlets.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>convservlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

这就是我告诉 spring 扫描组件的方式:

    <context:component-scan base-package="com.gim" />

出于某种原因,我的 Autowiring 对象 cobiService 为空。我忘了什么吗?我应该改变什么?

最佳答案

Servlet 不由Spring 管理,它们由Servlet 容器(如Tomcat)管理。因此 Spring 无法以正常的 Spring 方式将依赖项注入(inject) Servlet。但是,您可以执行以下操作:

public class MyServlet extends javax.servlet.http.HttpServlet {

private CobiService cobiService;

@Override
public void init() throws ServletException {
super.init();
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
cobiService = applicationContext.getBean(CobiService.class);
}

}

关于java - Spring MVC : autowire ignored in servlets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24057023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com