Spring框架学习—Spring的IOC基础知识
BeanFactory和ApplicationContext的区别
- BeanFactory:Spring框架的顶级接口,他只是用来定义一些基础功能,定义一些基础规范
- ApplicationContext是BeanFactory的子接口,随着继承的关系,ApplicationContext是具备BeanFactory提供的全部功能的
- 通常称BeanFactory为SpringIOC的基础容器,ApplicationContext是容器的高级接口,比BeanFactory拥有更多功能,比如:国际化支持,资源访问(xml文件,java配置类)等等
Spring IoC纯xml写法模式
- 使用
Spring IoC容器功能
需要引入的依赖<!--引入Spring IoC容器功能--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.12.RELEASE</version> </dependency>
- 通过Spring的核心图可以看到Spring把web部分单独放在一个地方,要在web环境中启动就要吧Spring-web包的依赖引入进来,有了web包的支持才可以使用Listener这个监听器去启动这个容器
- 在pom文件中引入依赖
<!--引入spring web功能--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.12.RELEASE</version> </dependency>
- 在web.xml中的配置:由于tomcat启动回去读取web.xml文件,里面有一个listener的组件,就会去执行/初始化这个监听器,监听器一执行就会进行一些SpringIoC容器启动的动作,我们的对象就可以进行管理了
<web-app> <display-name>Archetype Created Web Application</display-name> <!--配置Spring ioc容器的配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--使用监听器启动Spring的IOC容器, ContextLoaderListener要做初始化工作,要将xml文件读取进来,怎么将xml文件配置进来, 需要指定一个全局参数,contextConfigLocation,使用全局参数--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
- 在pom文件中引入依赖
Spring ioc 实例化Bean的三种方式
<!--方式一:使用无参构造器(推荐)-->
<bean id="connectionUtils" class="com.lagou.edu.utils.ConnectionUtils"></bean>
<!--另外两种方式是为了我们自己new的对象加入到SpringIOC容器管理-->
<!--方式二:静态方法-->
<bean id="connectionUtils" class="com.lagou.edu.factory.CreateBeanFactory"
factory-method="getInstanceStatic"/>
<!--方式三:实例化方法-->
<bean id="createBeanFactory" class="com.lagou.edu.factory.CreateBeanFactory"></bean>
<bean id="connectionUtils" factory-bean="createBeanFactory" factory-method="getInstance"/>
bean的作用范围以及生命周期
- 作用范围
实际开发当中,一般使用单例或多例模式比较多,例:<!--id标识对象,class是类的全限定类名--> <!--scope:定义bean的作用范围 singleton:单例,IOC容器中只有一个该类对象,默认为singleton prototype:原型(多例),每次使用该类的对象(getBean), 都返回给你一个新的对象,Spring只创建对象,不管理对象--> <bean id="transferService" class="com.lagou.service.impl.TransferServiceImpl" scope="singleton"> </bean>
- 生命周期
单例模式
:单例模式的bean对象生命周期与容器相同
多例模式
:多例模式的bean对象,Spring框架只负责创建,不负责销毁