Spring注解-LifeCycle-initMethod、destroyMethod

Spring注解-LifeCycle-initMethod、destroyMethod


生命周期-@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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值