xml配置高级使用
在Spring IOC - xml配置初级使用基础上新建spring_ioc_advanced.xml配置文件。
1. depends-on属性控制bean的加载顺序
xml配置属性
<!--控制bean的加载顺序 depends-on-->
<bean class="com.lazy.entity.User" id="user" depends-on="friend">
<property name="name" value="sky"/>
<property name="friends" ref="friend"/>
</bean>
<bean class="com.lazy.entity.Friend" name="friend">
<property name="name" value="cloud"/>
</bean>
获取bean,查看获取顺序
/*
* @Description: user对象依赖于friend对象,需要先加载friend
*/
@Test
public void testDependsOn() {
System.out.println("Spring容器已加载");
User user = ioc.getBean("user", User.class);
System.out.println(user);
Friend friend = ioc.getBean("friend",Friend.class);
System.out.println(friend);
}
Test:
2. lazy-init 懒加载
xml配置bean属性
<bean class="com.lazy.entity.Friend" id="lazy" lazy-init="true"/>
获取bean,查看加载顺序
/*
* @Description: 真正使用的时候加载bean
*/
@Test
public void testLazy() {
System.out.println("Spring容器已加载");
Friend friend = ioc.getBean("lazy",Friend.class);
System.out.println(friend);
}
Test:
3. Scope 作用域 默认单例singleton
xml配置bean属性
<!--scope 作用域
singleton 默认:单例 只会在Ioc容器种创建一次
prototype 多例(原型bean) 每次获取都会new一次新的bean
-->
<bean class="com.lazy.entity.User" name="userS" scope="prototype"/>
获取bean
/*
* @Description: 当scope设置为多例时,每获取一次加载一次
* 默认只会加载一次
*/
@Test
public void testScope() {
User user1 = ioc.getBean("userS", User.class);
User user2 = ioc.getB