SpringBoot:使用 @Lazy 注解懒加载

为什么需要懒加载?

我们知道,在 SpringBoot 应用程序启动的时候,会实例化一些对象加入到 IOC 容器里边,这个过程是非常耗时的,那我们想要减少这个耗时的过程就需要 @Lazy 注解

对象加入容器的时机

如下代码

package com.startdusk.forgot.service;

import org.springframework.stereotype.Component;

@Service
public class LazyService {
    public LazyService() {
        System.out.println("LazyService add to ioc container");
    }

    public void print() {
        System.out.println("lazy");
    }
}

由于我们在 LazyService 中打上了 @Service 注解,那么当程序启动的时候,LazyService 就会被立即实例化,我们在 LazyService 写了个无参的构造函数来测试,启动程序,会打印出


那么说明,在打上了 @Service 注解后,在程序启动的时候就立即实例化对象加入到容器

使用 @Lazy 延迟加入容器

那我们来改写下代码,延迟加入容器:

package com.startdusk.forgot.service;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
@Lazy
public class LazyService {
    public LazyService() {
        System.out.println("LazyService add to ioc container");
    }

    public void print() {
        System.out.println("lazy");
    }
}

再来运行一下程序:


看到运行的结果,并没有打印 "LazyService add to ioc container" 也就没有实例化 LazyService ,说明 @Lazy 注解起作用了,我们延迟了对象加入容器的时机

一个奇怪的现象

那么在实际情况中,我们会在 controller 中调用这个 service,即在 controller 中注入这个对象:

package com.startdusk.forgot.api.v1;

import com.startdusk.forgot.service.LazyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/v1/lazy")
public class LazyController {

    @Autowired
    private LazyService lazyService;

    @GetMapping("/test")
    public String test() {
        lazyService.print();
        return "Hello, world";
    }
}

保持 LazyService 中的 @Lazy,我们运行程序



发现 LazyService 居然被实例化了,难道打上 @Lazy 注解的类被注入之后 @Lazy 就不起作用了吗?我们来看下这个 LazyController 的代码,这里其实我们也把 LazyController 加入了容器(即打上了 @RestController 注解),在 SpringBoot 中,加入 IOC 容器就必须实例化对象,而实例化对象就要求,这个对象的里面的成员变量,方法都要被初始化,就包括 lazyService 这个要被注入的变量,即使 LazyService 打上了 @Lazy 注解。

解决这个问题,我们也需要在 LazyController 打上 @Lazy 注解,才能延迟加入 IOC 容器

package com.startdusk.forgot.api.v1;

import com.startdusk.forgot.service.LazyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/v1/lazy")
@Lazy
public class LazyController {

    @Autowired
    private LazyService lazyService;

    @GetMapping("/test")
    public String test() {
        lazyService.print();
        return "Hello, world";
    }
}

@Lazy 会延迟到什么时候

会延迟到对象被调用的时候。如,运行程序,访问 localhost:8080/v1/lazy/test 就是访问 test 这个方法,那么就会调用 lazyService.print() 就会打印出:


我们可以看到,当被注入的对象被调用的时候,才会把对象加入 IOC 容器,然后注入对象

使用 @Lazy 的缺点

我们来调整下代码:
LazyService 注释掉 @Service 和 @Lazy

package com.startdusk.forgot.service;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

// @Service
// @Lazy
public class LazyService {
    public LazyService() {
        System.out.println("LazyService add to ioc container");
    }

    public void print() {
        System.out.println("lazy");
    }
}

那么运行代码,再来访问下 localhost:8080/v1/lazy/test
,那么,程序会给我们抛一个错误:

Error creating bean with name 'lazyController': Unsatisfied dependency expressed through field 'lazyService';......

就是找不到这个这个注入的对象。那么这个报错是在程序运行中报错,而不是程序启动的时候就报错了。那么我们在 LazyController 中去掉 @Lazy

package com.startdusk.forgot.api.v1;

import com.startdusk.forgot.service.LazyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/v1/lazy")
public class LazyController {

    @Autowired
    private LazyService lazyService;

    @GetMapping("/test")
    public String test() {
        lazyService.print();
        return "Hello, world";
    }
}

启动程序,那么就会在程序启动的时候直接报错,不让你运行

Field lazyService in com.startdusk.forgot.api.v1.LazyController required a bean of type 'com.startdusk.forgot.service.LazyService' that could not be found.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,695评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,569评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,130评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,648评论 1 297
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,655评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,268评论 1 309
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,835评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,740评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,286评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,375评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,505评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,185评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,873评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,357评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,466评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,921评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,515评论 2 359

推荐阅读更多精彩内容