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();

    }
}

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

发布了56 篇原创文章 · 获赞 3 · 访问量 1182

猜你喜欢

转载自blog.csdn.net/qq_40788718/article/details/103337657
今日推荐