Spring default behavior for lazy-init

后端 未结 5 897
长发绾君心
长发绾君心 2020-12-07 20:00

I am beginner to spring, ESP Inversion of control. I was puzzled understanding the difference between the following

 

        
5条回答
  •  天涯浪人
    2020-12-07 20:44

    For those coming here and are using Java config you can set the Bean to lazy-init using annotations like this:

    In the configuration class:

    @Configuration
    // @Lazy - For all Beans to load lazily
    public class AppConf {
    
        @Bean
        @Lazy
        public Demo demo() {
            return new Demo();
        }
    }
    

    For component scanning and auto-wiring:

    @Component
    @Lazy
    public class Demo {
        ....
        ....
    }
    
    @Component
    public class B {
    
        @Autowired
        @Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
        private Demo demo;
    
        .......
     }
    

提交回复
热议问题