Spring入门
2019-01-16 本文已影响59人
若兮缘
容器是Spring框架的核心,Spring容器就是一个巨大的工厂。Spring容器使用IOC管理所有组成应用系统的组件
Spring容器是生成Bean实例的工厂,并管理容器中的Bean。Bean是Spring管理的基本单元
Spring容器会使用XML解析器读取属性值,并利用反射来创建该实现类的实例
核心接口
BeanFactory
这是一个基本工厂,提供配置结构和基本功能,用于生成任意bean。采取延迟加载,第一次getBean时才会初始化Bean
ApplicationContext
是BeanFactory的子接口,功能更强大。(国际化处理、事件传递、Bean自动装配、各种不同应用层的Context实现)。
当配置文件被加载,就进行对象实例化
获取sprin上下文方式:
说明:
ClassPathXmlApplicationContext
用于加载classpath(类路径、src)下的xml,加载xml运行时位置 --> /WEB-INF/classes/
FileSystemXmlApplicationContext
用于加载指定盘符下的xml,加载xml运行时位置 --> /WEB-INF/...xml(ServletContext.getRealPath())
1.本地文件: new FileSystemXmlApplicationContext(configLocation) 路径为文件在磁盘中的绝对路径
2.Classpath: new ClassPathXmlApplicationContext(configLocation) web工程中相对于WEB-INF/classes路径
3.Web应用中依赖Listener:
<!--通过ContextLoaderListener加载-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/configs/spring/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
4.Web应用中依赖servlet:
<!--通过ContextLoaderServlet加载-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/configs/spring/applicationContext*.xml</param-value>
</context-param>
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>