Bean的scope:
1、Singleton(单例): 一个Spring容器只有以这个Bean实例。
2、prototype(多例): 每次调用新建一个Bean的实例。
3、request:一个http request请求一个Bean实例。
4、Session:一个http session请求一个Bean实例。
5、GlobalSession:portal应用中有用
1 package com.wisely.heighlight_spring4.ch2.scope; 2 3 import org.springframework.context.annotation.Scope; 4 import org.springframework.stereotype.Service; 5 6 @Service 7 @Scope("singleton") //配置作用域单列(默认就是单列) 8 public class DemoSingletonService { 9 10 }
1 package com.wisely.heighlight_spring4.ch2.scope; 2 3 import org.springframework.context.annotation.Scope; 4 import org.springframework.stereotype.Service; 5 6 @Service 7 @Scope("prototype") //配置作用域是多列 8 public class DemoPrototypeService { 9 10 }
1 package com.wisely.heighlight_spring4.ch2.scope; 2 3 import org.springframework.context.annotation.ComponentScan; 4 import org.springframework.context.annotation.Configuration; 5 6 @Configuration 7 @ComponentScan("com.wisely.heighlight_spring4.ch2.scope") 8 public class ScopeConfig { 9 10 }
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))); } }