码迷,mamicode.com
首页 > 编程语言 > 详细

Spring在Web应用中使用的原理

时间:2014-10-29 23:34:40      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:io   ar   使用   java   sp   文件   on   问题   new   

那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();

Spring在Web应用中使用的原理

标签:io   ar   使用   java   sp   文件   on   问题   new   

原文地址:http://www.cnblogs.com/jeremy-blog/p/4060565.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!