關(guān)于Spring中@Lazy注解的使用
1、@Lazy注解是什么
@Lazy注解用于標識bean是否需要延遲加載,源碼如下:
@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; }
只有一個參數(shù),默認是true,也就是說只要加了這個注解就會延遲加載
2、@Lazy注解怎么使用
沒加注解之前主要容器啟動就會實例化bean,如下:
AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class);
而加上@Lazy注解則必須在第一次調(diào)用的時候才會加載如下:
/** * 定義一個bean對象 * @return */ @Scope @Lazy @Bean(value="user0",name="user0",initMethod="initUser",destroyMethod="destroyUser") public User getUser(){ System.out.println("創(chuàng)建user實例"); return new User("張三",26); }
AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class); User bean2 = applicationContext2.getBean(User.class);
創(chuàng)建user實例
實例1 === User [userName=張三, age=26]
@Lazy注解注解的作用主要是減少springIOC容器啟動的加載時間
到此這篇關(guān)于關(guān)于Spring中@Lazy注解的使用的文章就介紹到這了,更多相關(guān)Spring的@Lazy內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatis攔截器無法注入spring bean的問題解決
本文主要介紹了mybatis攔截器無法注入spring bean的問題解決,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-02-02SpringBoot+MyBatis實現(xiàn)MD5加密數(shù)據(jù)庫用戶密碼的方法
MD5技術(shù)主要用于對用戶密碼加密,增加賬戶的安全性,他具有不可逆的特性,不會被輕易解密,這篇文章給大家介紹SpringBoot+MyBatis實現(xiàn)MD5加密數(shù)據(jù)庫用戶密碼的方法,感興趣的朋友跟隨小編一起看看吧2024-03-03SpringBoot ThreadLocal 簡單介紹及使用詳解
ThreadLocal 叫做線程變量,意思是 ThreadLocal 中填充的變量屬于當前線程,該變量對其他線程而言是隔離的,也就是說該變量是當前線程獨有的變量,這篇文章主要介紹了SpringBoot ThreadLocal 的詳解,需要的朋友可以參考下2024-01-01SpringSecurity安全框架在SpringBoot框架中的使用詳解
在Spring?Boot框架中,Spring?Security是一個非常重要的組件,它可以幫助我們實現(xiàn)應(yīng)用程序的安全性,本文將詳細介紹Spring?Security在Spring?Boot框架中的使用,包括如何配置Spring?Security、如何實現(xiàn)身份驗證和授權(quán)、如何防止攻擊等2023-06-06