@Scope注解的范围
- Singleton:一个Spring容器只有一个Bean实例,也是默认配置
- Prototype:每次调用新建一个Bean实例
- Request:web项目中,每一个http request新建一个Bean实例
- Session:web项目中,每一个http session新建一个Bean实例
- GlobalSession:portal应用中使用
单例service类
import org.springframework.stereotype.Service;/** * @author Kevin * @description * @date 2016/6/30 */@Service// 默认为singleto 相当于@Scope("singleton")public class DemoSingletonService {}
Prototype service类
import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Service;/** * @author Kevin * @description * @date 2016/6/30 */@Service@Scope("prototype")public class DemoPrototypeService {}
配置类
import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;/** * @author Kevin * @description * @date 2016/6/30 */@Configuration// 扫描所在包@ComponentScan("ch02.scope")public class Config {}
运行
import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * @author Kevin * @description * @date 2016/6/30 */public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.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 == s2)); System.out.println("p1 == p2 : " + (p1 == p2)); }}
结果