我想使用Spring在servlet中注入一个对象

我的应用程序中有两个servlet,我希望将一个A类对象注入到两个servlet中,我也希望在整个应用程序中使用相同的ApplicationContext,即在SO的这个问题的第一个答案中提到的两个servlet: Spring注入Servlet

现在我经历了很多像这样的问题,但找不到与我的问题相符的东西。 为了更好地解释,我在这里写一个粗略的代码

public class servletOne extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } public class servletTwo extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } 

所以上面是applicationContext.xml中的两个servelts我想将一个对象传递给这两个servlet,因此按照惯例,我想要一个像这样的function:

         

我不知道这是否可能,我是spring新手,我只有dependency injection的基本知识。

如果有人能帮我这个,我真的很感激。 这将清除我的许多疑虑并帮助我在学习Spring的过程中向前迈进。

这是web.xml

   contextConfigLocation /WEB-INF/applicationContext.xml   org.springframework.web.context.ContextLoaderListener   dispatcher org.springframework.web.servlet.DispatcherServlet 2   servletOne mypackage.servletOne   servletTwo mypackage.servletTwo   dispatcher *.htm   servletOne /servletOne   servletTwo /servletTwo    300    

你混淆了两个概念:Servlets和Spring的ApplicationContext 。 Servlet由Servlet容器管理,让我们以Tomcat为例。 ApplicationContext由Spring管理。

在部署描述符中声明Servlet

  servletOne mypackage.servletOne   servletOne /servletOne  

Servlet容器将创建mypackage.servletOne类的实例,注册它,并使用它来处理请求。 这就是它对DispatcherServlet ,它是Spring MVC的基础。

Spring是一个IoC容器,它使用ApplicationContext来管理许多bean。 ContextLoaderListener加载根ApplicationContext (从您告诉它的任何位置)。 DispatcherServlet使用该根上下文,并且还必须加载它自己的上下文。 上下文必须具有DispatcherServlet的适当配置才能工作。

在Spring上下文中声明一个bean,比如

    

无论它与web.xml中声明的类型相同,都是完全不相关的。 上面的bean与web.xml中的声明无关。

正如我在这里的回答一样,因为ContextLoaderListener将它创建的ApplicationContext作为属性放入ServletContext中,所以ApplicationContext可用于任何Servlet容器管理对象。 因此,您可以在自定义HttpServlet类中重写HttpServlet#init(ServletConfig) ,如此

 @Override public void init(ServletConfig config) throws ServletException { super.init(config); ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); this.someObject = (SomeBean)ac.getBean("someBeanRef"); } 

假设您的根ApplicationContext包含一个名为someBeanRef的bean。

还有其他替代方案。 例如,这。

如果你想通过applicationContext.xml使用@Autowired或set属性,那么用@Controller注释注释你的类