Bean的Scope Scope描述的是Spring 容器如何创建Bean的示例。 通过@Scope注解来实现 Singleton:Spring容器只有一个Bean的实例,此为Spring的默认配置,全容器共享一个实例 Prototype:每次调用新建一个Bean的实例 Request:web项目中给每个http request新建一个Bean实例 Session:web项目中,给每个http session新建一个Bean实例 GlobalSession:只在portal应用中有用,给每一个global http session新建一个Bean实例 另外,在Spring Batch中还有一个Scope是使用@StepScope 编写代码的过程中发现 只有@Service创建bean 实例相同 如果在下面继续注解@Scope("prototype") 就会发现两个实例并不是相等的。 他们的内存空间不同
@Service
@Scope("prototype")
public class DemoPrototypeService {
}
@Service
public class DemoSingletonService {
}
@Configuration
@ComponentScan("com.example.demo.scope")
public class ScopeConfig {
}
@SpringBootApplication
public class DemoApplication {
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.err.println("s1 与 s2是否相等"+s1.equals(s2));
System.err.println("p1 与 p2是否相等"+p1.equals(p2));
context.close();
}
}
结果