Spring中的 @Lazy的简单理解

Spring IoC (ApplicationContext) 容器一般都会在启动的时候实例化所有单实例 bean 。如果我们想要 Spring 在启动的时候延迟加载 bean,即在调用某个 bean 的时候再去初始化,那么就可以使用 @Lazy 注解。需要注意的是对于作用域(scope)为原型prototype的,默认情况下,其实例并不会随着容器的启动而开始实例化,而是再用到的时候才会去实例化。@Lazy可以添加在类上,也可以添加在方法(或者bean)上。

@Lazy 的属性的使用

@Lazy(value = true)或者@Lazy(true)或者@Lazy,对于value取值有false和true,默认值为 true。而false个人认为纯属多余,如果不使用,不标注该注解就可以了。@Lazy注解注解的作用主要是减少springIOC容器启动的加载时间

当出现循环依赖时,也可以添加@Lazy。

举例说明:

package com.itheima.course.configuration;

/**
 * @description 
 * @date 2021-02-18 18:23:32
 */
public class OracleDataSource {
    public OracleDataSource() {
        System.out.println("Call OracleDataSource  constructor");
    }
}
package com.itheima.course.configuration;

/**
 * @description
 * @date 2021-02-18 18:22:30
 */
public class MysqlDataSource {
    public MysqlDataSource() {
        System.out.println("Call MysqlDataSource constructor");
    }
}
package com.itheima.course.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * @description configuration配置类
 * @date 2021-02-18 18:24:17
 */
@Configuration
// @Lazy
public class AppConfig {
    @Bean
    public MysqlDataSource mysqlDataSource() {
        oracleDataSource();
        return new MysqlDataSource();
    }

    @Bean
    public OracleDataSource oracleDataSource() {
        return new OracleDataSource();
    }
}
package com.itheima.course.configuration;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @description configuration详解举例
 * @date 2021-02-18 18:26:22
 */
public class TestAppconfig {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
        //MysqlDataSource mysqlDataSource1 = (MysqlDataSource) ac.getBean("mysqlDataSource");
    }
}

配置类添加@Lazy时的结果:没有结果输出

配置类不添加@Lazy时的结果:

Call OracleDataSource  constructor
Call MysqlDataSource constructor
经验分享 程序员 微信小程序 职场和发展