1、由spring创建的对象默认都是单例;
如果想要多例,配置的时候设置作用域属性:scope=“prototype”
<bean id="scopeBean" class="cn.itsource._03_scope.MyScopeBean" scope="prototype"/>
扩展:
===================================================================
2、Spring默认使用的是及时加载模式,即启动就会创建好所有的Bean对象,底层使用的是ApplicationContext容器;
如果想设置Spring为懒加载模式(即注入的时候再创建对象,底层使用的是BeanFactory容器):在文件的根对象中添加default-lazy-init为true
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="true">
</beans>
如果只是想设置单个Bean为懒加载模式:
<bean id="user" class="cn.itdemo.test.User" lazy-init="true"/>
===================================================================
3、Bean对象的生命周期
生命周期指的是:从对象创建、初始化、调用执行到销毁的一个过程;
实例化:Spring容器调用Bean的无参构造创建Bean对象
初始化:Spring容器调用指定的初始化方法
销毁:在Spring容器关闭的时候(ApplicationContext对象没有close方法,其实现类有),会自动调用指定的销毁方法(并不是真正意义上的销毁Bean对象);
P.s:多例的Bean对象是无法被销毁的,因为Spring并不知道什么时候会创建
自己可以指定Bean的初始化方法和销毁方法,但没什么意义
===================================================================
4、spring随着tomacat启动
Mybatis代替JDBC,作用于持久层;
SpringMVC代替servlet,作用于表现层;
而spring是作用于三层中,因为它这个框架集成了很多很多
在web项目中,配置web.xml
<!-- spring上下文监听器 -->
<!-- ContextLoaderListener extends ContextLoader implements ServletContextListener -->
<!--
ContextLoaderListener的作用就是启动Web容器时,读取在contextConfigLocation中定义的xml文件,
自动装配ApplicationContext的配置信息,并产生WebApplicationContext对象,【extends ApplicationContext】。
这样我们只要得到Servlet就可以得到WebApplicationContext对象,并利用这个对象使用spring容器管理的bean对象。
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载sprin的 配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>