• Spring在Web应用中使用的原理


    那Spring如何在web应用中使用
    ①加入Spring web应用的特定jar包spring-web-4.0.0.RELEASE.jar、spring-webmvc-4.0.0.RELEASE.jar
    ②添加Spring的配置文件----跟Java工程没有什么不一样
    ③如何实例化IOC容器
    I. 如果在非 WEB 应用在 main 方法中直接创建
    II 如果自web应用的话应该在 WEB 应用被服务器加载时就创建 IOC 容器
    那问题又来了,我怎么知道WEB应用什么时候被服务器加载呢?
    实际上在web应用都会有一个监听器专门监听web应用是否被服务器加载在 ServletContextListener
    也就说我们在这个监听器的监听web应用是否被加载的方法里里实例化IOC容器是最适合的吧
    也就说ServletContextListener#contextInitialized(ServletContextEvent sce) 方法中创建 IOC 容器.
    ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    III创建IOC容器后,Web应用的其它组件怎么取用IOC容器呢??这里放入Application=ServletContext里就可以吧,
    因为这个是共享对象吖,任何用户都可以调用
    ServletContext servletContext=arg0.getServletContext();
    servletContext.setAttribute("applicationContext", applicationContext);
    IV使用:
    //1. 从 application 域对象中得到 IOC 容器的引用
    ServletContext servletContext = getServletContext();
    ApplicationContext ctx = (ApplicationContext) servletContext.getAttribute("applicationContext");
    //2. 从 IOC 容器中得到需要的 bean
    person person = ctx.getBean(person.class);
    person.hello();

  • 相关阅读:
    Tarjan
    uestc 方老师的分身IV
    Fleury(弗罗莱)算法求欧拉回路
    515D
    uestc 方老师的分身 II
    uestc SOUND OF DESTINY
    uestc WHITE ALBUM
    双向BFS
    【Tomcat】【3】报错 Illegal access: this web application instance has been stopped already. Could not load [org.apache.commons.pool.impl.CursorableLinkedList$Cursor]
    【JS】【25】把字符串转换为数字
  • 原文地址:https://www.cnblogs.com/jeremy-blog/p/4060565.html
Copyright © 2020-2023  润新知