Bean的Scope
一、点睛
Scope描述的是Spring容器如何新建Bean的实例。Spring的Scope有以下几种,通过@Scope注解来实现
1、Singleton:一个Spring容器中有一个Bean的实例,此为Spring的默认配置全容器共享一个实例;
2、ProtoType:每次调用新建一个Bean的实例;
一、点睛
Scope描述的是Spring容器如何新建Bean的实例。Spring的Scope有以下几种,通过@Scope注解来实现
1、Singleton:一个Spring容器中有一个Bean的实例,此为Spring的默认配置全容器共享一个实例;
2、ProtoType:每次调用新建一个Bean的实例;
3、Request:web项目中给每一个http request新建一个Bean实例;
4、Session:web项目中给每一个http session新建一个Bean实例;
5、GlobalSession:这个只有在Portal应用中有用,给每一个golbal http session 新建一个Bean实例;
4、Session:web项目中给每一个http session新建一个Bean实例;
5、GlobalSession:这个只有在Portal应用中有用,给每一个golbal http session 新建一个Bean实例;
另外在Spring Batch 中还有一个Scope是使用@StepScope
演示默认的singleton和Prototype 分别从Spring 容器中获得2次Bean判断Bean的实例是否相等。
二、示例
(1)、编写 Singleton 的Bean
@Service
public class DemoSingletonService{};
代码解释:
1、默认为Singleton 相当于@Scope(“singleton”)
(2)、编写Prototype的Bean
@Service
演示默认的singleton和Prototype 分别从Spring 容器中获得2次Bean判断Bean的实例是否相等。
二、示例
(1)、编写 Singleton 的Bean
@Service
public class DemoSingletonService{};
代码解释:
1、默认为Singleton 相当于@Scope(“singleton”)
(2)、编写Prototype的Bean
@Service
@Scope(“prototype”)
public class DemoPrototypeService{};
public class DemoPrototypeService{};
代码解释:
1、声明Scope为Prototype
(3)、配置类
@Configuration
@ComponentScan();
public class Config{};
1、声明Scope为Prototype
(3)、配置类
@Configuration
@ComponentScan();
public class Config{};
(4)、运行
public static void main (String[] args){
AnnotationConfigApplicationContext context =new AnnotationConfigContext(ScopeConfig.class);
DemoSingletonService s1=context.getBean(DemoSingletonService.class);
DemoSingletonService s2=context.getBean(DemoSigletonService.class);
DemoPrototypeService p1= context.getBean(DemoPrototypeService.class);
DemoPrototypeService p2=context.getBean(DomePrototypeService.class);
System.out.println("s1和s2是否相等"+s1.equals(s2));
System.out,println("p1和p2是否相等"+p1.equals(p2));
context.close();
}
结果为:s1和s2是否相等 true
public static void main (String[] args){
AnnotationConfigApplicationContext context =new AnnotationConfigContext(ScopeConfig.class);
DemoSingletonService s1=context.getBean(DemoSingletonService.class);
DemoSingletonService s2=context.getBean(DemoSigletonService.class);
DemoPrototypeService p1= context.getBean(DemoPrototypeService.class);
DemoPrototypeService p2=context.getBean(DomePrototypeService.class);
System.out.println("s1和s2是否相等"+s1.equals(s2));
System.out,println("p1和p2是否相等"+p1.equals(p2));
context.close();
}
结果为:s1和s2是否相等 true
p1和p2是否相等 false