常见的两个作用域
spring在不指定Bean的作用域的的情况下默认都是singleton单例的,是饿汉式加载,在IOC容器启动就会直接加载。
- 未指定作用域,默认为单例的,是饿汉式加载对应的构造方法会被执行
@Configuration
public class MyConfig {
@Bean
public Person person() {
return new Person();
}
}
public class Demo {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
}
}
22:09:21.081 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myConfig'
22:09:21.081 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'person'
person的构造方法执行了...
Process finished with exit code 0
- 指定作用域为prototype后发现构造方法不会执行
@Configuration
public class MyConfig {
@Bean
@Scope(value = "prototype")
public Person person() {
return new Person();
}
}
22:10:24.761 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
22:10:24.764 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myConfig'
Process finished with exit code 0
prototype: 指定@Scope为理解为多例的,是懒汉式加载,IOC容器启动的时候不会去创建对象,而是在第一次使用的时候才会创建对象。(两次从IOC容器中获取到的对象也是不同的)
public class Demo {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
//从IOC容器中获取bean
Person person1 = context.getBean("person", Person.class);
Person person2 = context.getBean("person", Person.class);
System.out.println(person1 == person2);
}
}
23:27:32.798 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myConfig'
person的构造方法执行了...
person的构造方法执行了...
false
Process finished with exit code 0