(1)springIOC容器可以管理bean的生命周期。spring允许在bean生命周期的特定点执行定制的任务。
(2)spring的IOC容器对bean的生命周期进行管理的过程:
- 通过构造器或工厂方法创建bean的实例;
- 为bean的属性设置值并对其他bean的引用;
- 调用Bean的初始化方法;
- bean可以被使用了;
- 当容器关闭时,调用bean的销毁方法;
(3)当bean设置声明了init-method和destroy-method属性,为bean指定初始化和销毁方法。
Car.java
package com.gong.spring.beans.cycle; public class Car { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Car() { System.out.println( "car的构造器"); } public void init() { System.out.println("init..."); } public void destroy() { System.out.println("destroy..."); } @Override public String toString() { return "Car [name=" + name + "]"; } }
beans-cycle.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.gong.spring.beans.cycle.Car" init-method="init" destroy-method="destroy"> <property name="name" value="baoma"></property> </bean> </beans>
Main.java
package com.gong.spring.beans.cycle; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { //1.创建spring的IOC容器对象 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans-cycle.xml"); //2.从容器中获取Bean实例 Car car = (Car) ctx.getBean("car"); System.out.println(car.toString()); ctx.close(); } }
输出: