当前位置 博文首页 > 程序员石磊:Spring boot enable Lazy Initialization of bean

    程序员石磊:Spring boot enable Lazy Initialization of bean

    作者:[db:作者] 时间:2021-07-04 18:48

    概述

    • 当我们启用延迟初始化时,bean 将在需要时初始化,默认情况下在应用程序开始时初始化 bean。
    • 对于 web 应用程序,controller bean 将在该控制器上的第一个 HTTP 请求上进行初始化。
    • @Lazy(false) annotation 注释使用我们可以禁用特定 bean 的延迟。
    • NOTE: 如果在 Bean 初始化时配置错误,那么在应用程序启动时无法识别它,在这种情况下, 应用程序将成功启动,但是当初始化发生时,就会出现错误,只是因为这个原因,默认情况下,spring 延迟初始化为 false。

    For example:
    DemoController.Java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping
    public class DemoController {
    
        DemoController(){
            System.out.println("Controller init...");
        }
        
        @Autowired
        private EmployeeService employeeService;
    
        @RequestMapping("/demo")
        public String demo(){
            System.out.println("Preparing HTTP request...");
            return "This is from demo";
        }
    }
    

    EmployeeService.Java

    import org.springframework.stereotype.Service;
    
    @Service
    public class EmployeeService {
    
        public EmployeeService(){
            System.out.println("Service Init ...");
        }
    
    }
    

    输出:

    在第一个请求中,依赖 bean 将被初始化。
    wget http://localhost:8181/demo

    Controller init...
    Service Init ...
    Preparing HTTP request...
    

    启用 懒加载


    方法一: Enable lazy using application.properties

    truevalue 表示懒加载

    spring.main.lazy-initialization=true

    方法二: Enable lazy using SpringApplication

    truevalue 表示懒加载

    @SpringBootApplication
    public class SpringBootConfig {
        public static void main(String[] args) throws Exception {
            SpringApplication application = new SpringApplication(SpringBootConfig.class);
            application.setLazyInitialization(true);
            application.run();
        }
    }
    

    指定bean禁用懒加载

    @Service
    @Lazy(value = false)                // disable lazy for this bean
    public class EmployeeService {
    
        public EmployeeService(){
            System.out.println("Service Init ...");
        }
    
    }
    
    cs