Spring 多实例

@Configuration
public class BeanConfig {

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public String testPrototypeBean() {
        System.out.println("------>testPrototypeBean");
        return "testPrototypeBean";
    }
}
public class BeanConfigTest {

    @Test
    void testPrototypeBean() {
        ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
        Object bean1 = context.getBean("testPrototypeBean");
        Object bean2 = context.getBean("testPrototypeBean");
    }
}

输出:

------>testPrototypeBean
------>testPrototypeBean

所以testPrototypeBean()方法会重复执行,因此尽量不要在这个方法中执行耗时耗资源得方法,尤其是重复的数据库操作等,可以使用原型模式,把数据存储起来,在testPrototypeBean方法中克隆。
与其在testPrototypeBean方法中new对象,不如克隆快。当然大对象才有必要,小对象new就行。

posted @ 2020-11-11 15:26  qianbuhan  阅读(86)  评论(0)    收藏  举报