继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Spring 一二事(4) - 单例

2018-05-10 11:45:243379浏览

风间影月

8实战 · 53手记 · 8推荐
TA的实战

spring bean配置后再默认情况下是单例的,如果需要配置可以选择 prototype, request, session和global session

在配置spring mvc的action时,可以对action使用 prototype

<!-- singleton: 默认单例 prototype: 多例 request ,session和global session: 只适用于web程序 -->
    <bean id="scope_prototype" class="com.lee.spring005.scope.Scope"
        scope="prototype"></bean>

    <!-- destroy-method 一般在数据源的时候用到,关闭容易后就销毁连接 -->
    <bean id="initDestory" class="com.lee.spring006.init_destory.InitDestory"
        init-method="init" destroy-method="destory"></bean>

bean的创建销毁过程:

package com.lee.spring006.init_destory;

public class InitDestory {

    public InitDestory() {
        System.out.println("InitDestory() ");
    }

    public void hello() {
        System.out.println("Hello InitDestory!");
    }

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

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

测试:

@Test
    public void testInitDestory() {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        InitDestory initDestory = (InitDestory)context.getBean("initDestory");
        initDestory.hello();

        ClassPathXmlApplicationContext app = (ClassPathXmlApplicationContext)context;
        app.close();
    }
打开App,阅读手记
“小礼物走一走,来慕课关注我”
赞赏支持
风间影月说
去围观
创业公司技术总监, 10年+开发和技术管理经验。SUN认证SCJP、PMP、MCP认证。主要从事后端技术和架构领域,有丰富的电商平台与物流平台核心系统的架构设计和开发经验。
发表评论
随时随地看视频慕课网APP