當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
Spring系列(五):@Lazy懒加载注解用法介绍
生活随笔
收集整理的這篇文章主要介紹了
Spring系列(五):@Lazy懒加载注解用法介绍
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
今天給大家介紹@Lazy懶加載注解用法,希望對(duì)大家能有所幫助!
? ? ? ? ? ? ? ?
1、@Lazy 懶加載注解的概念
SpringIoC容器會(huì)在啟動(dòng)的時(shí)候?qū)嵗袉螌?shí)例 bean 。如果我們想要實(shí)現(xiàn) Spring 在啟動(dòng)的時(shí)候延遲加載 bean,即在首次調(diào)用bean的時(shí)候再去執(zhí)行初始化,就可以使用 @Lazy 注解來(lái)解決這個(gè)問(wèn)題。
注意:使用@Lazy的前提是要操作的Bean要使用默認(rèn)的單例模式。
2、@Lazy 懶加載注解作用
使用@Lazy懶加載注解可以減少springIOC容器啟動(dòng)過(guò)程的加載時(shí)間。
3、@Lazy 懶加載注解使用示例
3.1 新建配置類TestLazyConfig.java
package com.spring.config;import com.spring.bean.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component;@Configuration //@Lazy注解作用于類上時(shí),通常與@Component及其衍生Spring注解配合使用。 /*@Component @Lazy*/ public class TestLazyConfig {// @Lazy注解屬性 Value 取值為 true、false 。默認(rèn)為true 表示啟用懶加載。//false 表示不啟用,基本用不到,如果不啟用的話,不需要加@Lazy注解 // @Lazy注解作用于在類方法上時(shí),通常與@Bean注解配合使用。@Lazy@Beanpublic Person person() {System.out.println("測(cè)試容器添加Person對(duì)象......");return new Person("小孫", 28, "西安");} }3.2 新建測(cè)試類 TestLazy.java
package com.spring.test;import com.spring.config.TestLazyConfig; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestLazy {public static void main(String[] args) { // @Lazy 注解啟用的時(shí)候 不進(jìn)行類初始化, // 不啟用的時(shí)候會(huì)進(jìn)行類初始化 //控制臺(tái)輸出:測(cè)試容器添加Person對(duì)象...... AnnotationConfigApplicationContext annotationContext = new AnnotationConfigApplicationContext(TestLazyConfig.class); // 第一次獲取Bean對(duì)象 會(huì)進(jìn)行類初始化 //控制臺(tái)輸出:測(cè)試容器添加Person對(duì)象......Object person1 = annotationContext.getBean("person");// 第二次獲取Bean對(duì)應(yīng) 不會(huì)載進(jìn)行類初始化Object person2 = annotationContext.getBean("person");} }IT技術(shù)分享社區(qū)
個(gè)人博客網(wǎng)站:https://programmerblog.xyz
文章推薦程序員效率:畫流程圖常用的工具程序員效率:整理常用的在線筆記軟件遠(yuǎn)程辦公:常用的遠(yuǎn)程協(xié)助軟件,你都知道嗎?51單片機(jī)程序下載、ISP及串口基礎(chǔ)知識(shí)硬件:斷路器、接觸器、繼電器基礎(chǔ)知識(shí)
總結(jié)
以上是生活随笔為你收集整理的Spring系列(五):@Lazy懒加载注解用法介绍的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 中boxplot函数的参数设置_如何在P
- 下一篇: Spring系列(六):@Conditi