Spring bean创建细节 (二)
package com.matrix42.config;
/**
* Created by Matrix42 on 2017/5/6.
*/
public class User {
private int id;
private String name;
public void init(){
System.out.println("init()");
}
public void destory(){
System.out.printf("destory()");
}
public User() {
System.out.println("User.User()");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.matrix42.config;
import org.junit.Test;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
* Created by Matrix42 on 2017/5/6.
*/
public class UserTest {
@Test
public void testUser(){
//创建容器对象
//ApplicationContext ac = new FileSystemXmlApplicationContext("src/applicationContext.xml");
//会从当前类所在包下找applicationContext.xml 方便测试
//ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml",this.getClass());
//destory()方法在实现类中才有
FileSystemXmlApplicationContext ac = new FileSystemXmlApplicationContext("src/applicationContext.xml");
System.out.println("----------------------");
//单例模式下 容器初始化的时候bean对象已经创建 如果在初始化之后创建对第一个访问者就不公平了
//多例模式下 bean对象在容器初始化之后创建
User user = (User) ac.getBean("user");
User user2 = (User) ac.getBean("user2");
User user3 = (User) ac.getBean("user3");
User user4 = (User) ac.getBean("user4");
//销毁容器实例
ac.destroy();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--
把对象加入IOC容器
写id或name
id只能有一个,name比较灵活可以有多个值
id重复xml中会报错,但name不会在运行的时候会报错
scope="singleton"是默认值 getBean只会new一次
prototype表示多例
init-method="" 为初始化方法在对象创建完成后调用
destroy-method="" 为销毁方法 销毁的时候调用 在单例情况下并且执行容器对象的destory方法时才生效
lazy-init="false" 懒加载 只对单例模式生效
-->
<bean id="user" name="user2,user3 user4" class="com.matrix42.config.User" init-method="init" destroy-method="destory" scope="prototype" lazy-init="false"></bean>
</beans>
bean的生命周期
singleton
创建
-
lazy-init="true"
在容器初始化之后,第一次从容器获取对象的时候创建单例的对象
-
lazy-init="false"
在创建容器的时候创建对象
初始化
创建完对象后,就会执行初始化方法
销毁
调用容器的destory()方法,容器在销毁单例对象的实例的时候会调用destory-method对应的方法,此时bean对象会被销毁
prototype
创建
每次从容器获取对象的时候,都会创建新的对象
初始化
每次创建完对象后,就会执行初始化方法
销毁
java自动回收