Spring中@Scope作用域浅读

常见的两个作用域

spring在不指定Bean的作用域的的情况下默认都是singleton单例的,是饿汉式加载,在IOC容器启动就会直接加载。
  1. 未指定作用域,默认为单例的,是饿汉式加载对应的构造方法会被执行

@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
  1. 指定作用域为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
欢迎大家指出理解有误的地方,会及时修改,谢谢!

你可能感兴趣的:(Spring中@Scope作用域浅读)