Bean的Scope
点睛
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中有用,给每一个global http session新建一个Bean的实例。
另外,在Spring Batch中还有一个Scope是使用@StepScope。
示例
(1). 编写Singleton的Bean
import org.springframework.stereotype.Service;
@Service //1
public class DemoSingletonService {
}
代码解释:① 默认为Singleton,相当于@Scop(“singleton”)
(2). 编写Prototype的Bean
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Scope("prototype")//1
@Service
public class DemoPrototypeService {
}
代码解释:①声明Scope为Prototype
(3).配置类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.springdemo.springtest")
public class ScopeConfig {
}
(4).运行
import com.springdemo.springtest.config.ScopeConfig;
import com.springdemo.springtest.service.DemoPrototypeService;
import com.springdemo.springtest.service.DemoSingletonService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ScopeMaster {
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 p1 = context.getBean(DemoPrototypeService.class);
DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);
System.out.println("s1与s2是否相等:" + s1.equals(s2));
System.out.println("p1与p2是否相等:" + p1.equals(p2));
context.close();
}
}
结果如图: