03点睛Spring4.1-scope

3.1 scope

  • scope描述spring容器是怎么样新建类的实例的(bean);
  • 在spring中默认的scope是singleton,这意味着无论你在程序中多少地方使用这个bean,它们都共享唯一个实例;
  • spring内置的scope有如下几个:
    • singleton:一个spring容器中只有一个bean的实例;
    • prototype:每次调用新建一个bean的实例;
    • request:web项目中,每一个http request,新建一个bean实例;
    • session:web项目中,每一个http session,新建一个bean实例;
    • globalSession:这个只在portal应用中有用,每一个global http session,新建一个bean实例

3.2 演示

3.2.1 新建scope为singleton的类

package com.wisely.scope;

import org.springframework.stereotype.Service;

@Service//默认scope为singleton
public class DemoSingletonService {

}

3.2.2 新建scope为prototype的类

package com.wisely.scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
public class DemoPrototypeService {

}

3.2.3 测试

package com.wisely.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                  new AnnotationConfigApplicationContext("com.wisely.scope");
        //分别从spring容器里获得两次实例,为singleton时共享一个实例,用prototype是又新建了一个实例
        DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
        DemoSingletonService s2 = context.getBean(DemoSingletonService.class);

        DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
        DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);

        System.out.println("s1与s2是否相等:"+s1.equals(s2));
        System.out.println("p1与p2是否相等:"+p1.equals(p2));
        context.close();
    }

}

输出

s1与s2是否相等:true
p1与p2是否相等:false

新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。

 

京东地址:http://item.jd.com/11894632.html

当当地址:http://product.dangdang.com/23926195.html

亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6 

淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail

 

 

 

或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值