Spring常用配置 - Bean的Scope

一、Scope是什么?

Scope: 描述Spring容器如何创建Bean的实例

二、Scope具体内容

@Scope的value有5个,分别解释下:

@Scope意义
SingletonSpring的默认配置,一个Spring容器中只有一个Bean的实例
Prototype每次调用都会新建一个Bean的实例
RequestWeb项目中,会给每个http request新建一个Bean实例
SessionWeb项目中,会给每个http session新建一个Bean实例
GlobalSessionportal应用中使用,给每一个global http session新建一个Bean实例
三、ScopeDemo

Bean1

package com.cactus.demo.scope;

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

/**
 * Created by liruigao
 * Date: 2019-10-11 20:37
 * Description:
 * 声明为Bean
 * Scope默认为singleton,一个Spring容器中只会存在一个实例
 */

@Service
//@Scope("singleton")
public class BeanOne {
}

Bean2

package com.cactus.demo.scope;

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

/**
 * Created by liruigao
 * Date: 2019-10-11 20:37
 * Description:
 * 声明为Bean
 * Scope为prototype,此时每次调用都会新建一个实例
 */

@Service
@Scope("prototype")
public class BeanTwo {
}

配置类

package com.cactus.demo.scope;

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

/**
 * Created by liruigao
 * Date: 2019-10-11 20:41
 * Description:
 */

@Configuration
@ComponentScan("com.cactus.demo.scope")
public class ScopeConfig {
}

Main

package com.cactus.demo.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by liruigao
 * Date: 2019-10-11 20:42
 * Description:
 */


public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
        BeanOne one1 = context.getBean(BeanOne.class);
        BeanOne one2 = context.getBean(BeanOne.class);
        BeanTwo two1 = context.getBean(BeanTwo.class);
        BeanTwo two2 = context.getBean(BeanTwo.class);
        System.out.println("Is one1 and one2 the same?  " + one1.equals(one2));
        System.out.println("Is two1 and two2 the same?  " + two1.equals(two2));
        context.close();
    }
}

result
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜鹊先生Richard

随缘~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值