1、在 web.xml 中配置监听器
org.springframework.web.context.ContextLoaderListener
2、在 web.xml 中指定 IOC 容器(applicationContext.xml)的位置
如果不指定则默认加载 WEB-INF/applicationContext.xml ,即该文件必须 位于 WEB-INF 下 ,且命名必须为 applicationContext.xml
二、初始化 Servlet 中的对象contextConfigLocation classpath:applicationContext.xml, classpath:applicationContext-*.xml
1、初始化对象
2、原生的servlet中(非springMVC、strust等),MyServiceTest 实例化需在 init()方法中实现。
虽然已配置 bean ,但只是在 IOC 创建对象,在一次 request 请求中 servlet 容器中的 MyServiceTest 对象此时为 null ,需通过 IOC 重新赋值。
public class MyServletTest extends HttpServlet {
MyServiceTest serviceTest;
@Override
public void init() throws ServletException {
ApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
//初始化 serviceTest
serviceTest =webApplicationContext.getBean("serviceTest",MyServiceTest.class);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
serviceTest.test();
super.doPost(req, resp);
}
}



