推荐用法一:
使用javaWeb的三大组件之一的监听器来创建spring的ioc容器对象,在tomcat容器启动的时候就创建一个容器对象,并且只创建一次。
首先:
先写好我们的监听器类
为什么要用ServletContext对象来存储我们的容器对象呢,因为ServletContext代表了整个web应用,他的生命周期随着服务器的开启而产生,随着服务器的关闭而销毁。
@WebListener()
public class InitListener implements ServletContextListener,
HttpSessionListener, HttpSessionAttributeListener {
// Public constructor is required by servlet spec
public InitListener() {
}
// -------------------------------------------------------
// ServletContextListener implementation
// -------------------------------------------------------
public void contextInitialized(ServletContextEvent sce) {//服务器启动就会调用这个方法
/* This method is called when the servlet context is
initialized(when the Web application is deployed).
You can initialize servlet context related data here.
*/
ServletContext sct = sce.getServletContext();//拿到ServletContext域对象,存储变量
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
sct.setAttribute("ac",ctx);
System.out.println("服务器启动,加载对象");
}
public void contextDestroyed(ServletContextEvent sce) {//这个方法是服务器关闭的时候执行的,可以用来关闭容器,关闭与mysql的连接等等操作
/* This method is invoked when the Servlet Context
(the Web application) is undeployed or
Application Server shuts down.
*/
}
// -------------------------------------------------------
// HttpSessionListener implementation
// -------------------------------------------------------
public void sessionCreated(HttpSessionEvent se) {
/* Session is created. */
}
public void sessionDestroyed(HttpSessionEvent se) {
/* Session is destroyed. */
}
// -------------------------------------------------------
// HttpSessionAttributeListener implementation
// -------------------------------------------------------
public void attributeAdded(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is added to a session.
*/
}
public void attributeRemoved(HttpSessionBindingEvent sbe) {
/* This method is called when an attribute
is removed from a session.
*/
}
public void attributeReplaced(HttpSessionBindingEvent sbe) {
/* This method is invoked when an attibute
is replaced in a session.
*/
}
}
然后在web.xml中配置我们的监听器类,或者,如果你和我一样有打上@WebListener()注解就不用进行配置了。
<listener>
<listener-class>weleness.listener.InitListener</listener-class>
</listener>
获取域对象,获得容器对象
protected ApplicationContext ac;
@Override
public void init() throws ServletException {
ServletContext context = this.getServletContext();
ac = (ApplicationContext) context.getAttribute("ac");
}
我这里是写在我个人写的一个servlet的父类,下面用反射根据方法名称分发方法,所以我写在初始化方法里面,然后子类要注入对象的时候只要调用一下父类方法就可以了。
public class UserServlet extends BaseServlet {
private IUserService service;
@Override
public void init() throws ServletException {
super.init();
service = super.ac.getBean("userService",IUserService.class);
}