019 使用@Lazy完成懒加载

一 .概述

我们知道单实例Bean在spring的IOC容器之中,单实例Bean会在容器启动之后进行创建.

我们可以使用@Lazy完成懒加载,这样可以在初次获取Bean的时候才会创建Bean.


 二 .测试

public class Person {
    public Person() {
        System.out.println("Person 正在创建中....");
    }
}
@Configuration
public class LazyConfig {
    
    @Bean
    @Lazy
    public Person person() {
        return new Person();
    }
}

测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {LazyConfig.class})
public class LazyTest {
    
    @Autowired
    private ApplicationContext context;
    
    @Test
    public void test() throws Exception {
        System.out.println(context);
        TimeUnit.SECONDS.sleep(3);
        System.out.println(context.getBean("person"));
    }
}

我们创建完IOC容器之后,线程休眠3秒,然后我们从IOC中获取对象,我们发现此时

才真正的创建Bean.

这样就完成了懒加载的功能.

  懒加载,我们一般情况下是不会主动使用的.

posted @ 2018-05-27 00:16  最爱五仁月饼  阅读(116)  评论(0编辑  收藏  举报