Spring注解之@Scope

@Scope

@Scope是org.springframework.context.annotation包下的注解,指的是Ioc容器管理对象的作用域,基本作用域有(singleton,prototype),自定义作用域,Web 作用域(reqeust、session、globalsession)。

  1. singleton:单例模式,顾名思义,容器中只有一个bean实例对象。
  2. prototype:原型模式,使用时容器每次都会创建一个新的Bean实例对象。
  3. request:对于每次HTTP请求,使用request定义的Bean都将产生一个新实例,即每次HTTP请求将会产生不同的Bean实例。只有在Web应用中使用Spring时,该作用域才有效。
  4. session:对于每次HTTP Session,使用session定义的Bean都将产生一个新实例。同样只有在Web应用中使用Spring时,该作用域才有效。
  5. globalsession:每个全局的HTTP Session,使用session定义的Bean都将产生一个新实例。典型情况下,仅在使用portlet context的时候有效。同样只有在Web应用中使用Spring时,该作用域才有效。

注意
singleton作用域是Spring注解开发默认的,并且singleton的实例会被容器追踪并维护其生命周期,但是prototype的实例容器创建完之后,并不会追踪和管理。
因此singleton的实例会被重复使用,系统的开销会比较少,prototype就与之相反,但是还是要按照自己的需求来。

证明如下

package com.springboot.gyh.ch2.scope;

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

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

}
package com.springboot.gyh.ch2.scope;

import org.springframework.stereotype.Service ;

//默认的是scope("singleton")
@Service
public class DemoSingletonService {

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

//配置类
@Configuration
@ComponentScan("com.springboot.gyh.ch2")
public class ScopeConfig {
}

package com.springboot.gyh.ch2.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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 s3 = context.getBean(DemoPrototypeService.class) ;
        DemoPrototypeService s4 = context.getBean(DemoPrototypeService.class) ;

        System.out.println("s1是否s2相等:"+s1.equals(s2));
        //true
        System.out.println("s3是否s4相等:"+s3.equals(s4));
		//false
		
        context.close();

    }
}

运行结果如下:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值