IOC容器-Bean标签的生命周期方法

什么是生命周期呢?

一个件事物从生到死的过程,称之为生命周期。

使用bean标签属性

init-method="方法名" 
destroy-method="方法名"

案例

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Addr {
    private String addr;

    public void init() {
        System.out.println("初始化生命周期");
    }

    public void destroy() {
        System.out.println("销毁周期");
    }
}
<!-- 生命周期 -->
<bean init-method="init" destroy-method="destroy" id="addrs" class="com.spring.domain.Addr">
   <property name="addr" value="中国北京"></property>
</bean>
//生命周期测试
@Test
public void test4() {
   ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
   Addr addrs = (Addr) ac.getBean("addrs");
   System.out.println(addrs);
   ((ClassPathXmlApplicationContext) ac).close();
}

 

posted @ 2020-09-05 19:58  一半人生  阅读(174)  评论(0编辑  收藏  举报