Bean的Scope的简单示例
通过@Scope指定以下参数值
Singleton 单例的 (默认配置)
Prototype 多例的
Request web项目中request级别的单例
Session web项目中session级别的单例
GlobalSession portal应用(不知道是啥...)
- 新建一个Scope为Singleton的类
package com.xiaohan.scope;
import org.springframework.stereotype.Service;
@Service
// 可省略
// @Scope("singleton")
public class SingletonService {
}
- 新建一个Scope为Prototype的类
package com.xiaohan.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")
public class PrototypeService {
}
- 配置类
package com.xiaohan.scope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.xiaohan.scope")
public class ScopeConfig {
}
- Main测试
package com.xiaohan.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Bean的Scope
public class Main {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(ScopeConfig.class);
SingletonService s1 = ac.getBean(SingletonService.class);
SingletonService s2 = ac.getBean(SingletonService.class);
System.err.println(s1.equals(s2)); //true
PrototypeService p1 = ac.getBean(PrototypeService.class);
PrototypeService p2 = ac.getBean(PrototypeService.class);
System.err.println(p1.equals(p2)); //false
}
}
网友评论