Spring注解之@Lazy注解,源碼分析和總結


關於延遲加載的問題,有次和大神討論他會不會直接或間接影響其他類。spring的好處就是文檔都在代碼里,網上百度大多是無用功。

不如,直接看源碼。所以把當時源碼分析的思路丟上來一波。

 

二 源碼分析

/**
 * Indicates whether a bean is to be lazily initialized.
 * 用於bean的延遲加載
 * <p>May be used on any class directly or indirectly annotated with {@link
 * org.springframework.stereotype.Component @Component} or on methods annotated with
 * {@link Bean @Bean}.
 * 可以用於直接或間接使用的@Component類,或者@Bean方法
 * <p>If this annotation is not present on a {@code @Component} or {@code @Bean} definition,
 * eager initialization will occur. If present and set to {@code true}, the {@code @Bean} or
 * {@code @Component} will not be initialized until referenced by another bean or explicitly
 * retrieved from the enclosing {@link org.springframework.beans.factory.BeanFactory
 * BeanFactory}. If present and set to {@code false}, the bean will be instantiated on
 * startup by bean factories that perform eager initialization of singletons.
 * 如果沒有此注釋則會直接加載。(也就是說啟動的時候會按順序注入spring容器)反之,則會在被另一個bean引用或顯式引用前不會被初始化。
 * <p>If Lazy is present on a {@link Configuration @Configuration} class, this
 * indicates that all {@code @Bean} methods within that {@code @Configuration}
 * should be lazily initialized. If {@code @Lazy} is present and false on a {@code @Bean}
 * method within a {@code @Lazy}-annotated {@code @Configuration} class, this indicates
 * overriding the 'default lazy' behavior and that the bean should be eagerly initialized.
 * 如果@Configuration 上使用了Lazy,則@Configuration 中的所有都會被懶加載。若是沒使用,則對項目中的方法進行正常加載,哪怕在其他地方寫了Lazy。
* (因為spring默認注入順序先執行@Configuration ,那么就算后面使用了Lazy實際上也已經在spring容器中了)
* <p>In addition to its role for component initialization, this annotation may also be placed * on injection points marked with {
@link org.springframework.beans.factory.annotation.Autowired} * or {@link javax.inject.Inject}: In that context, it leads to the creation of a * lazy-resolution proxy for all affected dependencies, as an alternative to using * {@link org.springframework.beans.factory.ObjectFactory} or {@link javax.inject.Provider}.
* 除了作用於@Component組件或其@Bean初始化方法,也作用於InjectAutowired。在這種情況下,它會導致創建一個所有受影響的依賴項的延遲解析代理,作為使用的替代方法
* (就是Autowired注釋的bean會默認進行懶加載,除非他之前就被加載了,類似於@Configuration的情況)
*/ @Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Lazy { /** * Whether lazy initialization should occur. */ boolean value() default true;//也就是不用標簽是false,用就是true,網上什么@Lazy(true)大多是無謂代碼 }

三 總結

就是分兩種情況作用於 配置和其相關方法等先加載的 ,作用於 Autowired等后加載的。

特點有兩條

先加載的覆蓋后加載的。直接的覆蓋間接的。

第一條優先於第二條。

 

就是后加載的間接Bean若是在先加載的配置里被使用了,那么Lazy不起作用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM