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配置这个监听器,启动容器时,就会默认执行它实现的方法。


执行原理


0 0
原创粉丝点击