二、【注解】Spring注解@Scope

Spring容器中的Bean默认是单例的,可以使用@Scope来设置Bean的类型

/**
 * @author zhangjianbing
 * time 2020/09/23
 * https://www.zhangjianbing.com
 */
@Configuration
public class PersonConfig {

    /**
     * String SCOPE_SINGLETON = "singleton";单例
     * String SCOPE_PROTOTYPE = "prototype";多例
     * String SCOPE_REQUEST = "request";一次请求为一个对象
     * String SCOPE_SESSION = "session";一次会话为一个对象
     *
     * 单例:在容器初始化完成之前就已经将Bean实例化了
     * 多例:在使用对象的时候才会去实例化Bean
     */
    @Scope("prototype")
    @Bean
    public Person person() {
        return new Person("张三", 13);
    }

}

测试类:

public class MainTest {

    @Test
    public void m1() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
        Person person1 = applicationContext.getBean(Person.class);
        Person person2 = applicationContext.getBean(Person.class);
        System.out.println(person1 == person2);

        System.out.println("······容器初始化完成······");
    }

}

测试结果:
false
······容器初始化完成······
posted @ 2020-09-23 08:26  在谷歌上百度  阅读(151)  评论(0编辑  收藏  举报