我想使用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
注释注释你的类