在上一篇文章Spring之IOC_数字公民某杨的博客-CSDN博客
中使用spring后,示例代码中有两行
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
studentLoginService = (StudentLoginService) ac.getBean("studentLoginService");
这两行代码的意思是,获取spring容器 ac ,然后从ac对象中获取studentLoginService对象。
在这里有些技巧,
一个是ac这个spring容器对象创建好以后,实际只需要从里面获取studentLoginService对象,希望用垃圾回收机制尽快回收ac。
而当方法结束时,方法出栈,对对象的引用ac变量销毁,这样就启动java垃圾回收机制,回收原来ac指向的对象。如果还是放在servlet的service方法中,servlet对象只创建一次,但是service方法应该是多线程调用,所以会造成多次创建ac对象。而我们知道servlet有个init方法,是在servlet对象创建时调用,这样就想到把ac创建代码放在init方法中,我们有:
public class StudentServlet extends HttpServlet {
private StudentLoginService studentLoginService;
@Override
public void init() throws ServletException {
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
studentLoginService = (StudentLoginService) ac.getBean("studentLoginService");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String address = req.getParameter("address");
try {
Student student = studentLoginService.studentLogin(name, address);
HttpSession session = req.getSession();
ServletContext servletContext = this.getServletContext();
HttpSession tempSession = (HttpSession) servletContext.getAttribute(student.getId()+"");
if(tempSession!=null){
tempSession.invalidate();
}else {
servletContext.setAttribute(student.getId()+"", session);
}
session.setAttribute("student", student);
resp.sendRedirect("sucess.jsp");
}catch (Exception e){
resp.sendRedirect("error.jsp");
}
}
另一个技巧体现在web.xml配置文件中,先看下图:

我们有web.xml:
这个配置是说,在servletContext对象中保存以contextConfigLocation为key,以classpath:spring-config.xml为值的数据。这样当spring=config.xml后面需要修改的时候,就不需要去代码里面修改。
这个配置的意思是监听servletContext对象的创建,然后在监听器中,实现spring配置文件内容的读取。由于servlet对象只有1个,这样就减少了servlet创建多次时,对spring-config.xml文件的多次io操作