Spring注解驱动开发-part2生命周期

使用@Bean调用自定义的Bean初始化、销毁方法

在@Bean内部,可以指定initMethod和destroyMethod(调用bean内部的方法)

  • 定义Bean:

在这里插入图片描述

  • 增加配置类
    在这里插入图片描述
  • 测试

在这里插入图片描述在这里插入图片描述

  • 总结
    对于单实例Bean
    在容器关闭时,destory方法会被自动调用

实现InitializingBean和DisposableBean接口

在这里插入图片描述在这里插入图片描述
在这里插入图片描述

使用JSR250:PostConstruct 、PreDestroy

@PostConstruct : 在初始化完成后调用
@PreDestroy :在Bean被移除前调用

在这里插入图片描述

使用BeanPostProcessor

可以在初始化前后分步处理

在这里插入图片描述postProcessBeforeInitialization方法时机十分靠前,
在Bean的无参构造器调用之后调用,
在InitializingBean接口的内部方法afterPropertiesSet调用之前调用,
在JSR250规范的PostConstruct注解方法之前调用。

在这里插入图片描述
初始化Bean之前先要对bean进行属性填充。
populate Bean : 根据Bean定义信息,来填充Bean
initializeBean : 填充后再初始化Bean

在这里插入图片描述在调用自定义init初始化方法之前,先会调用BeanPostProcessorsBeforeInitialization,而init之后则会调用BeanPostProcessorsAfterInitialization。
在这里插入图片描述附:

实现其他BeanPostProcessor类型接口

在这里插入图片描述

在这里插入图片描述

package com.EzerbelCN.bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class Bird implements DisposableBean, InitializingBean,ApplicationContextAware {
	
	private ApplicationContext applicationContext;
	
	public Bird() {
		System.out.println("构造Bird");
	}
	public void afterPropertiesSet() throws Exception {
		System.out.println("Bird after Properties Set");
	}
	public void destroy() throws Exception {
		System.out.println("销毁Bird");
	}
	
	public void init_method() {
		System.out.println("Bird init");
	}
	public void destroy_method() {
		System.out.println("Bird destroy");
	}
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值