【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