Bean的Scope

Bean的scope:

1、Singleton(单例): 一个Spring容器只有以这个Bean实例。

2、prototype(多例): 每次调用新建一个Bean的实例。

3、request:一个http request请求一个Bean实例。

4、Session:一个http session请求一个Bean实例。

5、GlobalSession:portal应用中有用

 1 package com.wisely.heighlight_spring4.ch2.scope;
 2 
 3 import org.springframework.context.annotation.Scope;
 4 import org.springframework.stereotype.Service;
 5 
 6 @Service
 7 @Scope("singleton")        //配置作用域单列(默认就是单列)
 8 public class DemoSingletonService {
 9 
10 }
 1 package com.wisely.heighlight_spring4.ch2.scope;
 2 
 3 import org.springframework.context.annotation.Scope;
 4 import org.springframework.stereotype.Service;
 5 
 6 @Service
 7 @Scope("prototype")            //配置作用域是多列
 8 public class DemoPrototypeService {
 9 
10 }
 1 package com.wisely.heighlight_spring4.ch2.scope;
 2 
 3 import org.springframework.context.annotation.ComponentScan;
 4 import org.springframework.context.annotation.Configuration;
 5 
 6 @Configuration
 7 @ComponentScan("com.wisely.heighlight_spring4.ch2.scope")
 8 public class ScopeConfig {
 9 
10 }
package com.wisely.heighlight_spring4.ch2.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
        DemoSingletonService demoSingletonService1 = context.getBean(DemoSingletonService.class);
        DemoSingletonService demoSingletonService2 = context.getBean(DemoSingletonService.class);
        System.out.println("Singleton++++"+(demoSingletonService1.equals(demoSingletonService2)));
        
        DemoPrototypeService demoPrototypeService1 = context.getBean(DemoPrototypeService.class);
        DemoPrototypeService demoPrototypeService2 = context.getBean(DemoPrototypeService.class);
        System.out.println("prototype++++"+(demoPrototypeService1.equals(demoPrototypeService2)));
    }
}

 

转载于:https://www.cnblogs.com/JohnEricCheng/p/8618081.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值