生命周期-@Bean指定初始化和销毁方法
xml方法
init-method、estroy-method要求必须为无参方法。可以抛异常
<bean id="car" class="com.atguigu.bean.Car" scope="prototype" init-method="init" destroy-method="detory">
</bean>
注解方法
public class Car {
public Car(){
System.out.println("car constructor...");
}
public void init(){
System.out.println("car ... init...");
}
public void detory(){
System.out.println("car ... detory...");
}
}
配置类
/**
* bean的生命周期:
* bean创建---初始化----销毁的过程
* 容器管理bean的生命周期;
* 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
*
* 1)、指定初始化和销毁方法;
* 通过@Bean指定init-method和destroy-method;
*
*/
@ComponentScan("com.atguigu.bean")
@Configuration
public class MainConfigOfLifeCycle {
//@Scope("prototype")
@Bean(initMethod="init",destroyMethod="detory")
public Car car(){
return new Car();
}
}
运行结果
十二月 02, 2019 3:24:54 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1996cd68: startup date [Mon Dec 02 15:24:54 CST 2019]; root of context hierarchy
十二月 02, 2019 3:24:54 下午 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
car constructor...
car ... init...
容器创建完成...
car ... detory...
十二月 02, 2019 3:24:54 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose