(十二)生命周期-@PostConstruct和@PreDestroy

结论先行

可以使用JSR250规范
@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
@PreDestroy:在容器销毁bean之前通知我们进行清理工作

bean定义

package com.ouyangxizhu.bean;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

public class Dog {
    public Dog() {
        System.out.println("dog..............constructor");
    }
    @PostConstruct
    public void init(){
        System.out.println("dog..............@PostConstruct");
    }
    @PreDestroy
    public void destroy(){
        System.out.println("dog..............@PreDestroy");
    }
}

配置类

package com.ouyangxizhu.config;

import com.ouyangxizhu.bean.Dog;
import org.springframework.context.annotation.Bean;

public class MainConfigPostConstructPreDestroy {
    @Bean
    public Dog dog() {
        return new Dog();
    }
}

启动类

package com.ouyangxizhu.config;

import com.ouyangxizhu.bean.Dog;
import org.springframework.context.annotation.Bean;

public class MainConfigPostConstructPreDestroy {
    @Bean
    public Dog dog() {
        return new Dog();
    }
}

结果

八月 04, 2020 10:33:43 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@31cefde0: startup date [Tue Aug 04 22:33:43 CST 2020]; root of context hierarchy
dog..............constructor
dog..............@PostConstruct
八月 04, 2020 10:33:44 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@31cefde0: startup date [Tue Aug 04 22:33:43 CST 2020]; root of context hierarchy
dog..............@PreDestroy
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值