经测试,每次请求结束后,单例类中的静态属性还在,即使关闭窗口,单例类的静态属性依然存在,单例类的静态属性的生命周期与tomcat有关,当tomcat关闭的时候,
单例类的静态属性才会消失。。
线程何时终止:由于session的存在,线程的生命周期或许与session的生命周期有关。。
测试单例类的代码:
package com.zjlolife.util; import java.util.HashMap; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.zjlolife.domain.User; public class BeanFactory { private Document doc; private Map beans = new HashMap(); private static BeanFactory instance = new BeanFactory(); private BeanFactory() { try { doc = new SAXReader().read(Thread.currentThread() .getContextClassLoader() .getResourceAsStream("application-beans.xml")); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static BeanFactory getInstance() { System.out.println(instance); return instance; } @SuppressWarnings("unchecked") public Object getBean(Class c) { Object object = null; if (beans.containsKey(c.getName())) { object = beans.get(c.getName()); return object; } else { Element elt = (Element) doc.selectObject("//bean[@id=\"" + c.getName() + "\"]"); try { object = Class.forName(elt.attributeValue("class")) .newInstance(); beans.put(c.getName(), object); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return object; } public static void main(String [] args) { User user = (User)BeanFactory.getInstance().getBean(User.class); System.out.println(user); } }
<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="com.zjlolife.domain.User" class="com.zjlolife.domain.User" /> </beans>
package com.zjlolife.domain; public class User { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.zjlolife.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.zjlolife.domain.User; import com.zjlolife.util.BeanFactory; public class TestServlet extends HttpServlet { public TestServlet() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user =(User)BeanFactory.getInstance().getBean(User.class); System.out.println(user); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
测试效果:
只要tomcat没关闭,每个用户访问的BeanFactory的实例instance都是同一对象,因此BeanFactory中的User也是同一对象。。。
其实这笔记可以不做的!!!