亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Spring Boot中的懶加載:何時何地使用懶加載

在这篇博客中,我们将探讨 Spring Boot 中的懒加载初始化概念,以及如何使用“@Lazy”注解及其给应用带来的好处。

懒初始化是什么?

懒惰初始化是一种设计模式,将对象的创建推迟,直到真正需要时才创建。在Spring框架中,这意味着一个bean在首次被请求时才被实例化和初始化。这特别有助于缩短应用程序的启动时间,尤其是在有许多bean或某些bean创建成本较高的情况下。

“@Lazy” 注解

Spring 提供了 @Lazy 注解来实现懒加载。这个注解可以有多种使用方式:

1. 在定义 Bean 时使用 @Lazy

要在 bean 上使用“@Lazy”注解,只需在 bean 方法上加上“@Lazy”注解。

    import org.springframework.context.annotation.Bean;  
    import org.springframework.context.annotation.Configuration;  
    import org.springframework.context.annotation.Lazy;  

    @Configuration  
    public class 应用程序配置类 {  

        @Bean  
        @Lazy  
        public 测试Bean testBean() {  
            return new 测试Bean();  
        }  
    }

在这个例子中,只有在第一次请求时才会创建testBean

2. 在配置类中使用 @Lazy:

你也可以在类级别上使用 @Lazy,以表明配置中所有的 bean 都应懒加载。

    import org.springframework.context.annotation.Configuration;  
    import org.springframework.context.annotation.Lazy;  
    import org.springframework.context.annotation.Bean;  

    @Configuration  
    @Lazy  
    public class LazyConfig {  

        @Bean  
        public TestBean testBean() {  
            return new TestBean();  
        }  

        @Bean  
        public AnotherTestBean anotherTestBean() {  
            return new AnotherTestBean();  
        }  
    }

在此情况下,“testBean”和“anotherTestBean”将被延迟初始化。

3. 使用 @Lazy 注解在依赖项上

你可以用“@Lazy”注解来实现懒加载依赖,这样可以延迟解析依赖。

    import org.springframework.beans.factory.annotation.Autowired;  
    import org.springframework.context.annotation.Lazy;  
    import org.springframework.stereotype.Component;  

    @Component  
    public class TestComponent {  

        private final TestBean testBean;  

        @Autowired  
        public TestComponent(@Lazy TestBean testBean) {  
            this.testBean = testBean;  
        }  

        // 可以在这里添加更多方法  
    } 

这里,“testBean”仅在访问“TestComponent”时首次被访问时创建。

懒加载的好处有哪些
  1. 提升启动速度:通过延迟 bean 的创建直到实际需要时,可以缩短应用程序的初始启动时间。
  2. 资源管理:惰性初始化能更高效地管理资源,因为它只会实例化实际使用的 bean。
  3. 避免循环依赖:惰性初始化可以通过延迟创建 bean 来避免循环依赖。

结尾

通过使用“@Lazy”注解,你可以控制何时实例化和初始化 bean 实例。但是,需要小心使用此功能,并注意它可能对应用程序性能的影响。

参考资料

https://www.baeldung.com/spring-lazy-annotation

懒加载注解(来自 Spring 框架 6.1.10 API 的声明):包:org.springframework.context.annotation,注解类型:Lazy

Github : https://github.com/tharindu1998/lazy-annotation

栈学 🎓

感谢你一直读到最后。临走前,再跟你说几句:

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消