2 Spring运行机制
来源:互联网 发布:淘宝网汽车贴纸 编辑:程序博客网 时间:2024/06/08 05:45
在《1 搭建Spring环境中》,我们从头开始搭建了Spring环境,并通过Java控制台环境和Web环境测试。本章主要分析这两种测试方法的运行机制,让读者对Spring运作有更深入的了解。
1 Java环境运行机制
当我们使用JUnit测试运行test方法的时候,Spring到底做了什么事情呢?
第一步
获取资源文件夹【rsources】中的spring.xml配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"classpath:spring.xml"});
第二步
通过spring.xml配置文件获得UserServiceImpl对象
UserServiceI userService = (UserServiceI)ac.getBean("userService");
为什么通过配置文件可以获取userServiceImpl对象呢?
UserServiceImpl类在包ilv.service包中,我们在spring.xml配置文件中设置了:
<!-- 自动扫描dao和service包(自动注入) --><context:component-scan base-package="ilv.dao,ilv.service" />
且在定义UserServiceImpl类的时候使用了注解:
@Service(value="userService")
通过sping.xml配置文件和注解,Spring框架将会自动扫描ilv.dao和ilv.service包下的所有类, 发现注解后会将此注解的类作为bean,并以注解名命名此bean。当我们调用此bean的时候,Spring框架将会new出一个对象(控制反转,IoC),并将生成的对象注入调用者(即将生成的实例赋值给调用者中的变量,依赖注入)。这样,我们就把创建、维护、销毁对象的工作交给了Spring。
第三步
调用测试方法 userService.test(); 执行,打印测试语句。
三个步骤的执行如下图所示。
2 Web容器运行机制
第一步
制定spring配置文件,当启动Tomcat是,web容器依据web.xml配置加载spring.xml配置文件(相当于test中使用代码加载),如果是默认spring配置文件名:ApplicationContext.xml,容器将自动加载。在我们前一章中使用是自定义的spring配置文件。
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml </param-value></context-param>
第二步
添加监听器。
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
注意,不同的spring版本,监听器名字不同。
ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息(或自定义的xml配置文件)。因为它实现了 ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。
- 2 Spring运行机制
- Spring运行机制
- spring 入门 之运行机制
- Spring 注解 的运行机制
- spring中DispatcherServlet的运行机制
- Spring中DispatcherServlet的运行机制
- spring中dispatcherservlet的运行机制
- mfc运行机制2
- 2_JVM_运行机制
- 2 SSL/TSL 运行机制
- 运行机制
- Spring Cloud Zuul 的 route 运行机制分析
- 2 SparkStreaming运行机制和架构
- 初识JVM-JVM运行机制(2)
- struts1 struts2 spring 各自的运行机制,工作流程(整理)
- web项目加入Struts,Hibernate,Spring后的运行机制
- Spring框架运行机制(控制反转,依赖注入,面向切面AOP)
- spring代理对象的生成及运行机制源码解读
- 循环队列
- JAVA Hibernate工作原理及为什么要用
- mybatis实战教程(mybatis in action),mybatis入门到精通
- Java Web基础
- 【10】矩形覆盖
- 2 Spring运行机制
- POJ百练2798 (2进制转化16进制)
- Linux虚拟地址空间布局
- Redis与Memcached的区别
- mapper映射文件配置之insert、update、delete
- Python reportLab 生成PDF
- Spring DI的配置使用
- Ioc容器装配Bean(2)
- motorola虚拟AC路由ap一体配置记忆版