Bean的Scope

Bean的scope:

1、Singleton(单例): 一个Spring容器只有以这个Bean实例。

2、prototype(多例): 每次调用新建一个Bean的实例。

3、request:一个http request请求一个Bean实例。

4、Session:一个http session请求一个Bean实例。

5、GlobalSession:portal应用中有用

 package com.wisely.heighlight_spring4.ch2.scope;

 import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service; @Service
@Scope("singleton") //配置作用域单列(默认就是单列)
public class DemoSingletonService { }
 package com.wisely.heighlight_spring4.ch2.scope;

 import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service; @Service
@Scope("prototype") //配置作用域是多列
public class DemoPrototypeService { }
 package com.wisely.heighlight_spring4.ch2.scope;

 import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan("com.wisely.heighlight_spring4.ch2.scope")
public class ScopeConfig { }
package com.wisely.heighlight_spring4.ch2.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
DemoSingletonService demoSingletonService1 = context.getBean(DemoSingletonService.class);
DemoSingletonService demoSingletonService2 = context.getBean(DemoSingletonService.class);
System.out.println("Singleton++++"+(demoSingletonService1.equals(demoSingletonService2))); DemoPrototypeService demoPrototypeService1 = context.getBean(DemoPrototypeService.class);
DemoPrototypeService demoPrototypeService2 = context.getBean(DemoPrototypeService.class);
System.out.println("prototype++++"+(demoPrototypeService1.equals(demoPrototypeService2)));
}
}

Bean的Scope

上一篇:【转】INSTALL_FAILED_NO_MATCHING_ABIS 的解决办法


下一篇:DBA_Oracle Erp R12中文补丁安装升级(案例)