In general, the injection is done using spring, and in the service or SPRINGMVC, the spring's injected spring bean can be fetched in the form of annotations as shown below:
@Resource (name = "Userinfomapper")
Private Userinfomapper Userinfomapper;
But there are situations like how to get the object in a servlet, because SPRINGMVC is servlet-based, and all requests are processed first through a default servlet- Org.springframework.web.servlet.DispatcherServlet (this option must be configured when configuring SPRINGMVC in Web. xml), the manually created servlet cannot automatically get the injected bean. Need to get through ApplicationContext ApplicationContext:
This.xmlpacker = ((ixmlpacker) This.applicationContext.getBean ("Xmlpacker"));
The ApplicationContext method is to add a listener, which is initialized when the context is complete, and is implemented in the following way:
Inherit Servletcontextlistener, rewrite contextinitialized, assign value to Webctx.
Package com.casic.servlet;
Import javax.servlet.ServletContextEvent;
Import Javax.servlet.ServletContextListener;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.web.context.support.WebApplicationContextUtils;
public class Applicationcontextinit implements Servletcontextlistener {
private static ApplicationContext webctx = null;
public void contextdestroyed (Servletcontextevent event) {
}
public void contextinitialized (Servletcontextevent event) {
Webctx = Webapplicationcontextutils.getwebapplicationcontext (Event.getservletcontext ());
}
public static ApplicationContext Getwebapplicationcontext () {
return webctx;
}
public static void Setwebctx (ApplicationContext webctx) {
Webctx = Webctx;
}
}
adding listeners to Web. xml
<listener>
<listener-class>com.casic.servlet.ApplicationContextInit</listener-class>
</listener>
The servlet uses Applicationcontextinit.getwebapplicationcontext () in the Init () function to obtain
public void Init () throws Servletexception {
if (This.applicationcontext = = null) {
This.applicationcontext = Applicationcontextinit.getwebapplicationcontext ();
This.xmlpacker = ((ixmlpacker) This.applicationContext.getBean ("Xmlpacker"));
}
}
Servlet gets ApplicationContext