【Java】SpringBoot的bean懶加載@Lazy注解


注解說明

@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);
    }
}

 沒有打印出日志,說明對象初始化時沒有調用構造函數,沒有進行對象創建。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM