小村村长

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

SpringBean的生命周期

最近看到一个讲解文章附上链接:https://juejin.cn/post/7075168883744718856

Bean对象的生命周期:

复制代码
<!-- bean的生命周期:
    单例对象: 将创建的bean放入容器
        出生:容器创建,对象出生 配置文件加载完毕后,会立即创建bean对象,并存放到IOC容器中
        活着:只要容器在,对象就一直活着
        死亡:容器销毁,对象消亡
    特点:生命周期与容器相同 -->
<!-- 单例对象: init-method: 初始化方法 destroy-method: 销毁时调用的方法 -->
<!--<bean scope="singleton" init-method="initMethod" destroy-method="destoryMethod"
id="AccountService5" class="com.village.service.impl.AccountServiceImpl"></bean>
-->
<!--
多实例bean的生命周期:
创建时机:
从IOC容器中获取对象时
销毁时机:
等待GC回收
-->
<!--
    多例对象:
    出生:每次使用时创建
    活着:在使用过程中
    死亡:使用完成之后,等待垃圾回收器回收。
        多实例bean对象的生命周期
            scope的值必须为: prototype
-->

<bean scope="prototype" init-method="initMethod" destroy-method="destoryMethod"
id="AccountService6" class="com.village.service.impl.AccountServiceImpl"></bean>
复制代码

 

复制代码
package com.village.web;

import com.village.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanLifeClient {
    public static void main(String[] args) {

        /*ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService service = ac.getBean("AccountService5", AccountService.class);
        service.save();;
        // 关闭IOC容器
        ((ClassPathXmlApplicationContext) ac).close();*/

        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountService service = ac.getBean("AccountService6", AccountService.class);
        service.save();;
        // 关闭IOC容器
        ((ClassPathXmlApplicationContext) ac).close();
    }
}
复制代码

 

posted on   小村村长  阅读(43)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示