Spring之bean的生命周期

2024-01-03 12:49:23

1.基础概念

(1)生命周期
从创建到消亡的完整过程
(2)bean生命周期
bean从创建到销毁的整体过程
(3)bean生命周期控制
在bean创建后到销毁前做一些事情

2.定义bean初始化和销毁时的相关操作

(1)配置文件方式进行bean生命周期控制

package domain;

import lombok.Data;

@Data
public class People {
    private String name;
    private Integer age;
    private String eat;

    public void init() {
        System.out.println("init");
    }

    public void destroy() {
        System.out.println("destroy");
    }
}


package domain;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Demo {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new  ClassPathXmlApplicationContext("applicationContext.xml");
        ctx.registerShutdownHook();
        People people = (People) ctx.getBean("people");
        System.out.println(people);
    }
}
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="people" class="domain.People" init-method="init" destroy-method="destroy">
        <property name="name" value="小明"/>
        <property name="age" value="1"/>
        <property name="eat" value="吃饭"/>
    </bean>
</beans>

(2)使用接口进行bean生命周期控制

package domain;

import lombok.Data;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

@Data
public class People implements DisposableBean, InitializingBean {
    private String name;
    private Integer age;
    private String eat;


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

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("在set方法之后执行");
    }
}

<?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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="people" class="domain.People">
        <property name="name" value="小明"/>
        <property name="age" value="1"/>
        <property name="eat" value="吃饭"/>
    </bean>
</beans>

文章来源:https://blog.csdn.net/Lyhdreamer/article/details/135359128
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。