SpringBoot中的Bean懒加载————@Lazy
注解说明
-
使用注解: @Lazy 效果:一般情况下,Spring容器在启动时会创建所有的Bean对象,使用@Lazy注解可以将Bean对象的创建延迟到第一次使用Bean的时候
引入步骤
在类上加入@Lazy或者@@Lazy(value=true)
示例代码
Bean对象在容器启动时创建
通过代码结果打印可以看出,在Spring容器启动中,就执行了MyLazy对象的创建动作。
package com.markey.com.markey.annotations.Lazy; import org.springframework.stereotype.Component; @Component public class MyLazy { public MyLazy() { System.out.println("i am construct method of MyLazy"); } public void sayHello() { System.out.println("hello, i am MyLazy"); } }
package com.markey.annotations; import com.markey.com.markey.annotations.Lazy.MyLazy; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class MyLazyTest { @Autowired MyLazy myLazy; @Test public void MyLazyTest() { myLazy.sayHello(); } }
使用@Lazy,Bean对象在第一次使用时创建
通过代码结果打印可以看出,在调用MyLazy对象的方式时,才执行了MyLazy的构造方法
package com.markey.com.markey.annotations.Lazy; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; @Component @Lazy public class MyLazy { public MyLazy() { System.out.println("i am construct method of MyLazy"); } public void sayHello() { System.out.println("hello, i am MyLazy"); } }
上一篇:
IDEA上Java项目控制台中文乱码