zoukankan      html  css  js  c++  java
  • 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();

  • 相关阅读:
    How does “void *” differ in C and C++?
    Can we use function on left side of an expression in C and C++?
    apache配置局域网访问
    apache以天为单位生成日志
    尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
    IIS 处理程序“PageHandlerFactory-Integrated”
    IIS无法识别的属性targetFramework
    php开启短标签支持
    Notepad++配色方案
    vim常用操作整理
  • 原文地址:https://www.cnblogs.com/jeremy-blog/p/4060565.html
Copyright © 2011-2022 走看看