创建时机
scope=“singleton” 单例的bean 是在spring容器启动时创建
scope=“prototype” 原型bean 在获取bean时才会创建
赋值的时机
对象创建完成后做赋值的工作
初始化 – 对象赋值操作完成后 资源加载
销毁
spring容器关闭时 资源释放 只会帮我们销毁单例的bean 原型bean不归他管
bean的作用域 – 默认singleton 单例 全局只会创建一个当前类的对象
scope=“prototype” 原型bean 在获取bean时才会创建
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--
spring默认是单例的bean 但是可以调整作用域
scope="singleton" 单例的
scope="prototype" 原型的bean 每获取一次bean 就创建一个对象
init-method="" 指定类中的初始化方法
destroy-method="" 指定类中的销毁方法 只会调用所有单例的bean
以上两个方法 在指定完成后 会被自动调用
lazy-init="true" 懒加载 设置单例的bean在spring容器这种加载配置文件时 不创建对象 在使用getBean获取对象时再创建对应key的bean
-->
<bean id="student" class="cn.kgc.spring.entity.Student" init-method="init" destroy-method="destroy2" lazy-init="true">
<property name="username" value="张三"></property>
<property name="password" value="123"></property>
</bean>
</beans>
文件一旦启动,就会去创建对象
// 文件一旦启动,就会去创建对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
在单例模式下,两次getBean容器智慧创建一个对象
// 只会创建一个对象
Student student1 = (Student)context.getBean("student");
Student student2 = (Student)context.getBean("student");
System.out.println(student1==student2);
控制台输出
Student()无参构造被执行!
setUserName()
setPassword()
interface afterPropertiesSet()
true
在ProtoType模式下,每一次getBean都会创建一次对象
<bean id="student" class="cn.kgc.spring.entity.Student" scope="prototype">
<property name="username" value="张三"></property>
<property name="password" value="123"></property>
</bean>
// 文件一旦启动,就会去创建对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student1 = (Student)context.getBean("student");
Student student2 = (Student)context.getBean("student");
System.out.println(student1==student2);
控制台输出
Student()无参构造被执行!
setUserName()
setPassword()
interface afterPropertiesSet()
Student()无参构造被执行!
setUserName()
setPassword()
interface afterPropertiesSet()