Bean对象的生命周期

  1. 单例对象

    出生:当容器创建对象出生

    活着:只要容器还在,对象一直活着

    死亡:容器销毁,对象消亡

    总结:单例对象的生命周期和容器相同

  1. 多例对象

     出生:当我们使用对象时spring框架为我们创建 活着:只要使用就一直在活着

     死亡:当对象长时间不用,且没有别的对象使用时,由Java回收机制回收

  举个例子:单例对象

  package com.xuefei.service.impl;
   
   import com.xuefei.service.AccountService;
   
   /**
    * 账户业务层实现类
    */
   public class AccountServiceImpl implements AccountService {
   
       public void init(){
           System.out.println("对象初始化!");
       }
   
       public AccountServiceImpl() {
           System.out.println("对象创建了!");
       }
   
       public void destory(){
           System.out.println("对象销毁了!");
       }
   
       public void saveAccount() {
           
       }
   }
 <bean id="accountService" class="com.xuefei.factory.StaticFactory"
             factory-method="getAccountService" scope="singleton" init-method="init" destroy-method="destory"></bean>
 public class Client {
       public static void main(String[] args) {
        
           ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("beans.xml");        //因为我们需要调用close
           AccountService accountService = (AccountService) app.getBean("accountService");
           System.out.println(accountService);
           //手动销毁
           app.close();
       }
   }

  运行结果

  多例对象 将单例改成多例

   <bean id="accountService" class="com.xuefei.factory.StaticFactory"
             factory-method="getAccountService" scope="prototype" init-method="init" destroy-method="destory"></bean>

猜你喜欢

转载自www.cnblogs.com/lililixuefei/p/11874835.html