注解說明
@Lazy:一般情況下,Spring容器在啟動時會創建所有的Bean對象,使用@Lazy注解可以將Bean對象的創建延遲到第一次使用Bean的時候。
引用
在類上加入@Lazy或者@Lazy(value=true)
@Lazy默認為true,@Lazy(false)等同於不加@Lazy注解
示例
不加@Lazy
Student類
@Data @NoArgsConstructor public class Student { private String name; private String gender; public Student(String name, String gender) { System.out.println("對象創建"); this.name = name; this.gender = gender; } }
配置類不加@Lazy注解測試
public class TestLazy { @Bean public Student getStudent(){ return new Student("張三","男"); } @Test public void test(){ ApplicationContext ctx = new AnnotationConfigApplicationContext(TestLazy.class); } }
Bean對象在容器啟動時創建,打印出了日志。
加上@Lazy注解
public class TestLazy { @Bean @Lazy public Student getStudent(){ return new Student("張三","男"); } @Test public void test(){ ApplicationContext ctx = new AnnotationConfigApplicationContext(TestLazy.class); } }
沒有打印出日志,說明對象初始化時沒有調用構造函數,沒有進行對象創建。