Bean的作用域概述
Bean的作用域就是指Spring中Java Bean 有效范围,其中最为常用的作用域有2种:
- 单例作用域(singleton):Bean的默认作用域,任何时候获得的Bean对象都是同一个实例
- 原型作用域(prototype):每次引到bean时都会创建新的实例
可以通过@Scope注解来设置Bean的作用域,该注解可以添加在类前(与@Component注解搭配使用),也可以添加在方法前(与@Bean注解搭配使用)。
Bean的其他类型的作用域如下表所示(了解即可):
Bean的作用域示例
在cn.highedu包下新建SingletonBean:
- import org.springframework.stereotype.Component;
- @Component
- public class SingletonBean {
- @Override
- public String toString() {
- return "SingletonBean";
- }
- }
在cn.highedu.spring包下新建PrototypeBean:
- import org.springframework.context.annotation.Scope;
- import org.springframework.stereotype.Component;
- @Component
- @Scope("prototype")
- public class PrototypeBean {
- @Override
- public String toString() {
- return "PrototypeBean";
- }
- }
在cn.highedu包下新建ScopeTest类,对Bean的作用域进行测试:
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
- public class ScopeTest {
- public static void main(String[] args) {
- ApplicationContext context =
- new AnnotationConfigApplicationContext(ContextConfig.class);
- // 测试默认的Scope
- SingletonBean bean1 = context.getBean(SingletonBean.class);
- SingletonBean bean2 = context.getBean(SingletonBean.class);
- System.out.println("bean1 和 bean2 是否是同一个对象:" + (bean1 == bean2));
- // 测试prototype
- PrototypeBean bean3 = context.getBean(PrototypeBean.class);
- PrototypeBean bean4 = context.getBean(PrototypeBean.class);
- System.out.println("bean3 和 bean4 是否是同一个对象:" + (bean3 == bean4));
- }
- }