配置Bean的初始化与销毁方法 与init前后的处理

普通Java程序需要使用((AbstractApplicationContext)context).close();显式指定关闭spring容器,destory方法才会运行

  1. 普通Bean对象通过init-methoddestroy-method指定初始化与销毁方法
public class Student implements Serializable {
	
	//......

    public void init(){
        log.debug("init...");
    }

    public void destory(){
        log.debug("destory...");
    }
}

注解:

@Bean(initMethod = "init",destroyMethod = "destory")
    public Student student(){
        return new Student();
    }

xml:

<bean class="com.hjf.student.entity.Student" id="student" init-method="init" destroy-method="destory"/>

组件形式的注解:

  • 通过@PostConstruct@PreDestroy指定初始化和销毁方法
@Data
@Slf4j
@Service
public class MybatisCardServiceImpl implements MybatisCardService {

    @PostConstruct
    public void init(){
        log.debug("init...");
    }

    @PreDestroy
    public void destory(){
        log.debug("destory...");
    }
}
  • 实现接口方式:通过实现InitializingBeanafterPropertiesSet()方法和DisposableBeandestroy()方法指定初始化和销毁
@Component
@Slf4j
public class SomeClass implements InitializingBean, DisposableBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        log.debug("init...");
    }

    @Override
    public void destroy() throws Exception {
        log.debug("destory");
    }
}



初始化前后的处理:实现BeanPostProcessor类,该接口的实现类会拦截spring容器内所有的bean,并在init方法执行前调用postProcessBeforeInitialization(),在init方法执行后调用postProcessAfterInitialization()

@Component
@Slf4j
public class SomeClass implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Student) {
            log.debug("after construct before init");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Student) {
            log.debug("after init");
        }
        return bean;
    }
}

运行结果如下:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值