Spring之bean的生命周期

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);
    }
}

<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方法之后执行");
    }
}


<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>

你可能感兴趣的:(Spring,spring,java,servlet)