@Scope
@Scope是org.springframework.context.annotation包下的注解,指的是Ioc容器管理对象的作用域,基本作用域有(singleton,prototype),自定义作用域,Web 作用域(reqeust、session、globalsession)。
- singleton:单例模式,顾名思义,容器中只有一个bean实例对象。
- prototype:原型模式,使用时容器每次都会创建一个新的Bean实例对象。
- request:对于每次HTTP请求,使用request定义的Bean都将产生一个新实例,即每次HTTP请求将会产生不同的Bean实例。只有在Web应用中使用Spring时,该作用域才有效。
- session:对于每次HTTP Session,使用session定义的Bean都将产生一个新实例。同样只有在Web应用中使用Spring时,该作用域才有效。
- 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();
}
}
运行结果如下: