Spring之IOC容器的生命周期
1.实体类
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Calendar; public class Car { private String brand; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public void init() throws IOException{ BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("./a.txt",true)); bw.write("method init "+Calendar.HOUR+":"+Calendar.MINUTE+":"+Calendar.SECOND+":"+Calendar.MILLISECOND); bw.flush(); bw.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ bw.close(); } } public void destroy() throws IOException{ BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("./a.txt",true)); bw.write("method destroy "+Calendar.HOUR+":"+Calendar.MINUTE+":"+Calendar.SECOND+":"+Calendar.MILLISECOND); bw.flush(); bw.newLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ bw.close(); } } }
2.XML文件
<?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"> <bean id="car" class="com.auguigu.spring.beans.cycle.Car" init-method="init" destroy-method="destroy"> <property name="brand" value="Audi"></property> </bean> </beans>
3.测试Main
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("./beans-cycle.xml"); Car car = (Car) ctx.getBean("car"); System.out.println(car); ctx.close(); } }
4.输出结果:
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. com.auguigu.spring.beans.cycle.Car@32dcb03b file.txt method init 18 method destroy 18
Spring IOC容器对bean的生命周期进行管理的过程
① 通过构造器或工厂方法创建bean实例
② 为bean的属性设置值和对其他bean的引用
③ 将bean实例化并传递给postProcessBeforeinitialization方法
④ 调用bean的初始化方法
⑤ 将bean实例化并传递给postProcessAfterinitialization方法
⑥ 使用bean
⑦ 容器关闭,调用bean的销毁方法