《Spring6》第11节:bean标签之init-method和destroy-methon属性

内容分享2小时前发布
0 0 0

《Spring6》第11节:bean标签常见属性介绍之init-method和destroy-methon属性

前面已经介绍了Spring中Bean实例化和依赖注入的相关内容,信任各位小伙伴应该对Spring框架已经有了初步的了解,这一小节让我们一起继续学习Spring的相关内容。

在前几个小节里面,我们在XML配置文件频繁的使用到了<bean>标签,这个标签可以说是Spring中的核心标签之一,后续几个小节的内容,我将逐一介绍<bean>标签中的相关属性,这一个小节介绍init-methoddestroy-method属性。

1.1、init-method属性

init-method属性的作用:指定初始化方法名称,当Bean对象实例化完成之后,就会调用这个init-method属性指定的方法,完成初始化的操作。如果我们有需求要在Bean对象使用之前,做一些业务逻辑的初始化处理,那么我们可以思考将这块代码写在初始化方法里面。

注意:init-method初始化方法,需要定义在当前Bean对象里面,并且是没有方法参数的。初始化方法只会调用一次。

1.2、destroy-method属性

destroy-method属性的作用:指定销毁之前调用的方法名称,当Bean对象不再被使用,或者IOC容器停止之前,会调用Bean对象的销毁方法,这个销毁方法就是通过destroy-method属性指定的。

  • PS:根据我自己在开发过程中的经验,销毁方法很少使用到,初始化方法有可能会使用到

注意:destroy-method销毁方法,需要定义在当前Bean对象里面,并且是没有方法参数的。销毁方法只会调用一次。

1.3、案例代码

下面就通过案例代码,来看下如何使用init-methoddestroy-method两个属性。

  • 第一,创建AService类,并且在该类中定义两个方法,分别是:init()方法destroy()方法
public class AService {
    public AService() {
        System.out.println("1、实例化[AService]类...");
    }

    /**
     * 初始化方法,在对象实例化完成之后,会调用这个方法
     */
    public void init() {
        System.out.println("2、调用[AService]类的init()初始化方法...");
    }

    /**
     * 销毁方法,在对象或者IOC容器销毁之前,会调用这个方法
     */
    public void destroy() {
        System.out.println("4、调用[AService]类的[destroy()]销毁方法...");
    }
}
  • 接着添加XML配置信息,通过init-methoddestry-method两个属性,分别是指定初始化方法和销毁方法名称。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 https://www.springframework.org/schema/beans/spring-beans.xsd">
  <!--
    定义bean
    使用 init-method 属性,指定初始化方法
    使用 destroy-method 属性,指定销毁方法
  -->
  <bean id="aService" class="com.spring.study.AService" init-method="init" destroy-method="destroy"/>
</beans>
  • 编写测试类,获取AService对象的实例。
public class TestCode {
    public static void main(String[] args) {
        // 1、创建IOC容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 2、获取bean
        AService aService = context.getBean(AService.class);
        System.out.println("3、使用Bean阶段,当前对象:" + aService);
        // 3、调用 close 方法,关闭IOC容器,即:模拟IOC容器的销毁,这样才可以触发 destroy 方法
        context.close();
    }
}

运行结果如下所示:

《Spring6》第11节:bean标签之init-method和destroy-methon属性

1.4、源代码获取

源代码地址:

https://gitcode.com/knowledge-base/spring-study/tree/spring6-chapter-11

到此,Spring中<bean>标签的init-methoddestroy-method属性就介绍完了。

今天就到这里,未完待续~~

© 版权声明

相关文章

暂无评论

none
暂无评论...