简单介绍Spring Bean的生命周期

Bean的生命周期

      一个对象的生命周期包括创建(实例化与初始化),使用以及销毁等阶段,在Spring中,Bean对象周期也遵循这一过程,但是Spring提供了许多对外接口,允许开发者对3个过程(实例化、初始化、销毁)的前后做一些操作,在Spring Bean中,实例化是为Bean对象开辟空间,初始化则是对属性的初始化。

      简单说一下Spring容器singleton、prototype作用域Bean的生命周期

singleton作用域下

     singleton作用域下Spring能够精确知道Bean何时被创建,何时初始化完成,以及何时销毁

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    


    <bean id="S" class="com.abc.s1.SImpl" scope="singleton" init-method="init" destroy-method="destroy"></bean>

</beans>
package com.abc.s1;

public interface S {
    void saveAccount();
    void init();
    void destroy();
}
package com.abc.s1;

public class SImpl implements S{

    public SImpl(){
        System.out.println("对象创建了");
    }



    @Override
    public void saveAccount() {
        System.out.println("service中的SaveAccount方法执行了。。。");
    }

    @Override
    public void init() {
        System.out.println("对象初始化了、。。");

    }

    @Override
    public void destroy() {
        System.out.println("对象销毁了。。");

    }
}
package com.abc.s1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {



        //1.获取核心容器对象
        ClassPathXmlApplicationContext ac= new ClassPathXmlApplicationContext("spring-mvc.xml");
        //2.根据id获取Bean对象
        S as = (S) ac.getBean("S");
        as.saveAccount();
        ac.close();
    }
}

 

 prototype作用域下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">




    <bean id="S" class="com.abc.s1.SImpl" scope="prototype" init-method="init" destroy-method="destroy"></bean>

</beans>

 

没有被销毁

 

 

总结::

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值