Spring系列 lazy註解

2021-09-29 21:05:05 字數 1091 閱讀 3212

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")

@bean

public region getregion()

@bean

public country getcountry()

}

測試用例:

@test

public void givenlazyannotation_whenconfigclass_thenlazyall()

正如我們所看到的,只有當我們第一次請求它們時才會建立所有bean:

然後我們將它新增到所需bean的配置中:

@bean

@lazy(true)

public region getregion()

2.2 使用@autowired

這裡,為了初始化乙個懶惰的bean,我們從另乙個bean中引用它。

我們想要懶惰載入的bean:

@lazy

@component

public class city

}public class region

public city getcityinstance()

}請注意,@ lazy在兩個地方都是強制性的。

使用city類上的@component註解並在使用@autowired引用它時:

spring註解之 Lazy註解

1,lazy註解是什麼 lazy註解用於標識bean是否需要延遲載入,原始碼如下 target retention retentionpolicy.runtime documented public inte ce lazy只有乙個引數,預設是true,也就是說只要加了這個註解就會延遲載入 2,la...

spring系列相關註解說明

其一 controller public class usercontroller 這時的方法 login 能處理的 url 請求路徑是基於 web 應用的,也就是 http localhost springmvc login,也就是 index.jsp 頁面中的 user login 鏈結位址應該...

Spring註解 Import註解

常用的匯入註解分類 註冊自己寫的類service dao controller可用包掃瞄 元件標註註解 controller service repository component bean 匯入的第三方包裡面的元件 import 快速給容器中匯入乙個元件 1 import 要匯入到容器中的元件 ...