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
······容器初始化完成······

相关文章:

  • 2021-12-11
  • 2021-09-04
  • 2019-07-15
  • 2021-05-24
  • 2022-02-10
  • 2021-06-05
  • 2021-07-27
  • 2021-11-19
猜你喜欢
  • 2022-12-23
  • 2021-05-24
  • 2021-06-12
  • 2021-11-30
  • 2021-05-31
  • 2021-12-10
相关资源
相似解决方案