0
点赞
收藏
分享

微信扫一扫

Spring注解:InitializingBean和DisposableBean

江南北 2021-10-15 阅读 64
技术分享

在Bean的生命周期中,自定义初始化和销毁方法,除了使用@Bean注解的initMethod和destroyMethod属性之外,Spring还提供了两个接口方法,分别是InitializingBean和DisposableBean。

InitializingBean
public interface InitializingBean {

    /**
     * Invoked by the containing {@code BeanFactory} after it has set all bean properties
     * and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
     * <p>This method allows the bean instance to perform validation of its overall
     * configuration and final initialization when all bean properties have been set.
     * @throws Exception in the event of misconfiguration (such as failure to set an
     * essential property) or if initialization fails for any other reason
     */
    void afterPropertiesSet() throws Exception;

}

InitializingBean的作用时机在于,对象创建并将所有的属性设置完成后,进行初始化,其初始化方法就是afterPropertiesSet方法。

DisposableBean
public interface DisposableBean {

    /**
     * Invoked by the containing {@code BeanFactory} on destruction of a bean.
     * @throws Exception in case of shutdown errors. Exceptions will get logged
     * but not rethrown to allow other beans to release their resources as well.
     */
    void destroy() throws Exception;

}

DisposableBean 的作用时机就是当容器关闭的时候,调用destroy方法执行销毁。

自定义Bean,实现InitializingBean和DisposableBean
@Component
public class Teacher implements InitializingBean, DisposableBean {

    public Teacher() {
        System.out.println("Teacher 构造器");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("Teacher 销毁");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Teacher 初始化");
    }
}
@Configuration
@ComponentScan("com.caiyq.spring.annotation.bean")
public class MainConfig {

}

测试

@Test
public void testBean() {
    AnnotationConfigApplicationContext applicationContext =
            new AnnotationConfigApplicationContext(MainConfig.class);
    System.out.println("容器创建完成");
    //关闭容器
    applicationContext.close();
}
Teacher 构造器
Teacher 初始化
容器创建完成

Teacher 销毁

在afterPropertiesSet和destroy方法中,可实现具体的业务逻辑。

举报

相关推荐

0 条评论