Scope描述的是Spring容器如何新建Bean的实例。Spring的Scope有以下几种,通过@Scope注解来实现。
- (1)Singleton: 一个Spring容器中只有一个Bean的实例,此为Spring的默认配置。全容器共享一个实例。
- (2) Prototype: 每次调用新建一个bean的实例。
- (3) Request: Web项目中,给每一个http request新建一个实例。
- (4) Session: Web项目中,给每一个http session新建一个实例。
- (5) GlobalSession: 这个只在portal应用中有用,给每一个global http session新建一个Bean实例。
另外,在Spring Batch中还有一个Scope是使用@StepScope。本例简单演示默认的singleton和prototype,分别从Spring容器中获得2次Bean,判断Bean的实例是否相等。
示例:
(1)编写Singleton的Bean。
package com.wisely.highlight_spring.ch2.scope;
import org.springframework.stereotype.Service;
@Service //默认为Singleton,相当于@Scope("singleton")。
public class DemoSingletonService {
}
(2)编写Prototype的Bean。
package com.wisely.highlight_spring.ch2.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service //声明为spring的一个bean
@Scope("prototype") //声明Scope为prototype:声明作用域为普通类型
public class DemoPrototypeService {
}
(3)配置类
package com.wisely.highlight_spring.ch2.scope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //声明是一个配置类
@ComponentScan("com.wisely.highlight_spring.ch2.scope")
public class ScopeConfig {
}
(4)运行
package com.wisely.highlight_spring.ch2.scope;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author baiyue
*
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ScopeConfig.class);
DemoSingletonService service1 = context.getBean(DemoSingletonService.class);
DemoSingletonService service2 = context.getBean(DemoSingletonService.class);
DemoPrototypeService service3 = context.getBean(DemoPrototypeService.class);
DemoPrototypeService service4 = context.getBean(DemoPrototypeService.class);
System.out.println("service1=service2 "+ service1.equals(service2));
System.out.println("service1=service2 "+ service3.equals(service4));
System.out.println(service1.hashCode());
System.out.println(service2.hashCode());
System.out.println(service3.hashCode());
System.out.println(service4.hashCode());
context.close();
}
}
结果如图所示:
八月 16, 2018 3:06:31 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@bebdb06: startup date [Thu Aug 16 15:06:31 CST 2018]; root of context hierarchy
service1=service2 true
service1=service2 false
231977479
231977479
1427889191
93314457
八月 16, 2018 3:06:31 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@bebdb06: startup date [Thu Aug 16 15:06:31 CST 2018]; root of context hierarchy