javascript
Spring@懒惰注释
介紹:
默認(rèn)情況下, Spring框架在應(yīng)用程序啟動(dòng)時(shí)加載并熱切初始化所有bean。 在我們的應(yīng)用程序中,我們可能有一些非常消耗資源的bean。 我們寧愿根據(jù)需要加載此類bean。 我們可以使用Spring @Lazy批注實(shí)現(xiàn)此目的 。
在本教程中,我們將學(xué)習(xí)如何使用@Lazy注釋延遲加載我們的bean。
延遲初始化:
如果我們用@Lazy注釋標(biāo)記我們的Spring配置類,那么所有帶有@Bean注釋的已定義bean將被延遲加載:
@Configuration @ComponentScan (basePackages = "com.programmergirl.university" ) @Lazy public class AppConfig { ?@Bean public Student student() { return new Student(); } ?@Bean public Teacher teacher() { return new Teacher(); } }通過在方法級別使用此注釋,我們還可以延遲加載單個(gè)bean:
@Bean @Lazy public Teacher teacher() { return new Teacher(); }測試延遲加載:
讓我們通過運(yùn)行應(yīng)用程序來快速測試此功能:
public class SampleApp { private static final Logger LOG = Logger.getLogger(SampleApp. class ); public static void main(String args[]) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig. class ); ????????LOG.info( "Application Context is already up" ); ?// Beans in our Config class lazily loaded Teacher teacherLazilyLoaded = context.getBean(Teacher. class ); Student studentLazilyLoaded = context.getBean(Student. class ); } }在控制臺上,我們將看到:
Bean factory for ...AnnotationConfigApplicationContext: ...DefaultListableBeanFactory: [...] ... Application Context is already up Inside Teacher Constructor Inside Student Constructor顯然, Spring在需要時(shí)而不是在設(shè)置應(yīng)用程序上下文時(shí)初始化了Student和Teacher Bean。
使用
我們還可以在注入點(diǎn)使用@Lazy批注:構(gòu)造函數(shù),setter或字段級。
假設(shè)我們有一個(gè)要延遲加載的Classroom類:
@Component @Lazy public class Classroom { public Classroom() { System.out.println( "Inside Classroom Constructor" ); } ... }然后通過@Autowired注釋將其連接到University bean:
@Component public class University { ?@Lazy @Autowired private Classroom classroom; ?public University() { System.out.println( "Inside University Constructor" ); } ?public void useClassroomBean() { this .classroom.getDetails(); ... } }在這里,我們懶惰地注入了Classroom bean。 因此,在實(shí)例化University對象時(shí),Spring將創(chuàng)建代理Classroom對象并將其映射到該對象。 最后,當(dāng)我們調(diào)用useClassroomBean()時(shí) ,才創(chuàng)建實(shí)際的Classroom實(shí)例:
// in our main() method AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); ? LOG.info( "Application Context is already up" ); ? University university = context.getBean(University. class ); LOG.info( "Time to use the actual classroom bean..." ); university.useClassroomBean();上面的代碼將產(chǎn)生以下日志:
Bean factory for ...AnnotationConfigApplicationContext: ...DefaultListableBeanFactory: [...] ... Inside University Constructor ... Application Context is already up Time to use the actual classroom bean... Inside Classroom Constructor如我們所見, Classroom對象的實(shí)例化被延遲,直到其實(shí)際需要為止。
請注意,對于延遲注入,我們必須在組件類以及注入點(diǎn)上都使用@Lazy批注。
結(jié)論:
在本快速教程中,我們學(xué)習(xí)了如何延遲加載Spring Bean。 我們討論了延遲初始化和延遲注入。
翻譯自: https://www.javacodegeeks.com/2019/09/spring-lazy-annotation.html
總結(jié)
以上是生活随笔為你收集整理的Spring@懒惰注释的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蔚来智能座舱发布“应用商店”,40 余款
- 下一篇: jit 和 jvm_关于JVM和JIT的