04-SpringBoot——Spring常用配置-Bean的Scope

Spring常用配置-Bean的Scope


【博文目录>>>】


【项目源码>>>】


【Bean的Scope】

Scope 描述的是Spring 容器如何新建Bean 的实例的。Spring 的Scope 有以下几种,通过@Scope 注解来实现。

1.  Singleton :一个Spring 容器中只有一个Bean 的实例,此为Spring 的默认配置,全容器共享一个实例。
2.  Prototype :每次调用新建一个Bean 的实例。
3.  Request: Web 项目中,给每一个http request 新建一个Bean 实例。
4.  Session: Web 项目中,给每一个http session 新建一个Bean 实例。
5.  Global Session :这个只在portal 应用中有用,给每一个global http session 新建一个Bean
实例。
6.  在Spring Batch 中还有一个Scope 是使用@StepScope 

【代码实现】

package com.example.spring.framework.scope;

import org.springframework.stereotype.Service;

/**
 * 默认为Singleton ,相当于@Scope(“singleton”)
 * Author: 王俊超
 * Date: 2017-07-10 22:38
 * All Rights Reserved !!!
 */
@Service
public class DemoSingletonService {
}
package com.example.spring.framework.scope;

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

/**
 * Author: 王俊超
 * Date: 2017-07-10 22:38
 * All Rights Reserved !!!
 */
@Service
@Scope("prototype")
public class DemoPrototypeService {
}
package com.example.spring.framework.scope;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Author: 王俊超
 * Date: 2017-07-10 22:39
 * All Rights Reserved !!!
 */
@Configuration
@ComponentScan("com.example.spring.framework.scope")
public class ScopeConfig {
}
package com.example.spring.framework.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Author: 王俊超
 * Date: 2017-07-10 22:40
 * All Rights Reserved !!!
 */
public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(ScopeConfig.class);
        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();
    }
}

【运行结果】

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值