Spring中的@scope注解

        Scope,也称作用域,在 Spring IoC 容器是指其创建的 Bean 对象相对于其他 Bean 对象的请求可见范围。在 Spring IoC 容器中具有以下几种作用域:基本作用域(singleton、prototype),Web 作用域(reqeust、session、globalsession),自定义作用域。

  1. singleton: 一个spring容器只有一个bean的实例,此为spring的默认配置
  2. prototype: 每次通过getBean方法取得的prototype都会新建一个bean实例
  3. request: 给每个http request新建一个bean实例
  4. session: 给每个http session新建一个bean实例
  5. GlobalSession: 这个只在portal应用中用,给每个global http session新建一个bean实例

下面就是通过代码解释基本作用域singleton与prototype的区别

创建SingletonService类:

package com.example.testdemo.service;

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

@Service
//@Scope(value = "singleton") spring默认
public class SingletonService {
}

创建PrototypeService类:

package com.example.testdemo.service;

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

@Service
@Scope(value = "prototype")
public class PrototypeService {
}

创建ScopeConfig类

package com.example.testdemo.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

@Component
@ComponentScan("com.example.testdemo.service")
public class ScopeConfig {
}

创建启动类:

package com.example.testdemo;

import com.example.testdemo.config.ScopeConfig;
import com.example.testdemo.service.PrototypeService;
import com.example.testdemo.service.SingletonService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class TestdemoApplication {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(ScopeConfig.class);
        SingletonService a1=context.getBean(SingletonService.class);
        SingletonService a2=context.getBean(SingletonService.class);
        PrototypeService b1=context.getBean(PrototypeService.class);
        PrototypeService b2=context.getBean(PrototypeService.class);
        System.out.println("a1是否等于a2:"+a1.equals(a2));
        System.out.println("b1是否等于b2:"+b1.equals(b2));
    }
}

运行结果为:

从而验证了singleton与prototype的区别

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值