Bean的生命周期
一个对象的生命周期包括创建(实例化与初始化),使用以及销毁等阶段,在Spring中,Bean对象周期也遵循这一过程,但是Spring提供了许多对外接口,允许开发者对3个过程(实例化、初始化、销毁)的前后做一些操作,在Spring Bean中,实例化是为Bean对象开辟空间,初始化则是对属性的初始化。
简单说一下Spring容器singleton、prototype作用域Bean的生命周期
singleton作用域下
singleton作用域下Spring能够精确知道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"
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 https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="S" class="com.abc.s1.SImpl" scope="singleton" init-method="init" destroy-method="destroy"></bean>
</beans>
package com.abc.s1;
public interface S {
void saveAccount();
void init();
void destroy();
}
package com.abc.s1;
public class SImpl implements S{
public SImpl(){
System.out.println("对象创建了");
}
@Override
public void saveAccount() {
System.out.println("service中的SaveAccount方法执行了。。。");
}
@Override
public void init() {
System.out.println("对象初始化了、。。");
}
@Override
public void destroy() {
System.out.println("对象销毁了。。");
}
}
package com.abc.s1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//1.获取核心容器对象
ClassPathXmlApplicationContext ac= new ClassPathXmlApplicationContext("spring-mvc.xml");
//2.根据id获取Bean对象
S as = (S) ac.getBean("S");
as.saveAccount();
ac.close();
}
}
prototype作用域下
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="S" class="com.abc.s1.SImpl" scope="prototype" init-method="init" destroy-method="destroy"></bean>
</beans>
没有被销毁
总结::