Spring IOC产生对象的时机
1、配置文件如下:1
2<bean id="helloWorld" class="..." ></bean>
<bean id="helloWorld2" class="..." ></bean>
说明:
1、只要声明一个bean,spring容器就会为之创建对象,不管class是否相同
2、在默认情况下,在启动spring容器的时候创建对象
3、把service层和dao层所有的类放入spring容器中,在启动spring容器的时候创建对象
4、可以过早的检查发现错误
5、缺点:如果该类中有属性,并且属性为一个集合,那么在创建对象的时候,集合中如果有数据了,那么该数据会过早的加入到内存中
为了避免上述情况的发生,尽量把数据放在局部变量中
(通过代理来做,需要的时候再加载)1
2
3
4
5
6
7
8
9
10
public class SystemProperties{
private Properties properties;
public void initProperties(){
properties = ...;
}
}
系统初始化的时候,加载数据库系统配置文件到Properties类中
2、配置延迟加载:1
<bean id="helloWorld" class="..." lazy-init="true"></bean>
default:默认=否
false:否,spring启动时创建对象
ture:是,调用时才创建对象
在多例的情况下,不论是否设置lazy-init,都是在调用的时候才创建对象1
<bean id="helloWorld" class="..." scope="prototype" lazy-init="ture"></bean>