Spring系列——@lazy注解

https://blog.csdn.net/m0_37941483/article/details/90679524

1.概述
默认情况下,Spring会在应用程序上下文的启动时创建所有单例bean。这背后的原因很简单:立即避免和检测所有可能的错误,而不是在运行时。
但是,有些情况下我们需要创建一个bean,而不是在应用程序上下文启动时,而是在我们请求时。
在这个快速教程中,我们将讨论Spring的@Lazy注释。

2.懒加载
这个注解出现在Spring 3.0以后,有好几种方法实现来懒加载实例化bean.

2.1 @Configuration class
@Configuraiton 和@lazy 一起使用时,意味着所有使用@Bean 的方法都是懒加载

@Lazy
@Configuration
@ComponentScan(basePackages = "com.baeldung.lazy")
public class AppConfig {
 
    @Bean
    public Region getRegion(){
        return new Region();
    }
 
    @Bean
    public Country getCountry(){
        return new Country();
    }
}


测试用例:

@Test
public void givenLazyAnnotation_whenConfigClass_thenLazyAll() 

你可能感兴趣的:(spring)