3

Spring系列(五):@Lazy懒加载注解用法介绍

 2 years ago
source link: https://blog.51cto.com/itShareArea/5081958
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

​今天给大家介绍@Lazy懒加载注解用法,希望对大家能有所帮助!​

Spring系列(五):@Lazy懒加载注解用法介绍_类初始化

​1、@Lazy 懒加载注解的概念​

​SpringIoC容器会在启动的时候实例化所有单实例 bean 。如果我们想要实现 Spring 在启动的时候延迟加载 bean,即在首次调用bean的时候再去执行初始化,就可以使用 @Lazy 注解来解决这个问题。​

​注意:使用@Lazy的前提是要操作的Bean要使用默认的单例模式。​

​2、@Lazy 懒加载注解作用​

​使用@Lazy懒加载注解可以减少springIOC容器启动过程的加载时间。​

​3、@Lazy 懒加载注解使用示例​

​3.1 新建配置类TestLazyConfig.java​

package com.spring.config;

import com.spring.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Configuration
//@Lazy注解作用于类上时,通常与@Component及其衍生Spring注解配合使用。
/*@Component
@Lazy*/
public class TestLazyConfig {
// @Lazy注解属性 Value 取值为 true、false 。默认为true 表示启用懒加载。
//false 表示不启用,基本用不到,如果不启用的话,不需要加@Lazy注解
// @Lazy注解作用于在类方法上时,通常与@Bean注解配合使用。
@Lazy
@Bean
public Person person() {
System.out.println("测试容器添加Person对象......");
return new Person("小孙", 28, "西安");
}
}

​3.2 新建测试类 TestLazy.java​

package com.spring.test;

import com.spring.config.TestLazyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestLazy {
public static void main(String[] args) {
// @Lazy 注解启用的时候 不进行类初始化,
// 不启用的时候会进行类初始化
//控制台输出: 测试容器添加Person对象......
AnnotationConfigApplicationContext annotationContext = new AnnotationConfigApplicationContext(TestLazyConfig.class);
// 第一次获取Bean对象 会进行类初始化
//控制台输出: 测试容器添加Person对象......
Object person1 = annotationContext.getBean("person");
// 第二次获取Bean对应 不会载进行类初始化
Object person2 = annotationContext.getBean("person");
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK