1

How can I set this attribute in my JavaConfig application context?

<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>
toiepp
  • 85
  • 6

1 Answers1

1

The Spring org.springframework.context.annotation.Lazy annotation indicates whether a bean is to be lazily initialized.

You can add it to a @Configuration class, a @Bean method or a @Component (for example @Service annotated class)

Example for a single bean:

@Configuration
public class MyConfig {

   @Bean
   @Lazy
   public Example myLayzBean() {
        return new Example();
   }
  
}

Example for all beans in one configuration class

@Configuration
@Lazy
public class MyConfig {

   @Bean
   public Example1 myLayzBean1() {
        return new Example1();
   }

   @Bean
   public Example2 myLayzBean2() {
        return new Example2();
   }
  
}

Example for bean found by component scan

@Service
@Lazy
public class Example3 {
  
}
Eugene
  • 117,005
  • 15
  • 201
  • 306
Ralph
  • 118,862
  • 56
  • 287
  • 383
  • I knew that. But if I have like 500 beans, and I what each of them to be lazy initialized, can't i just annotate `MyConfig` class so all beans in this context would be Lazy? – toiepp Feb 26 '22 at 10:05
  • @toiepp I added more examples, for different configuration scenarios. – Ralph Feb 26 '22 at 10:17
  • Lol, didn's think about that. Thank you! – toiepp Feb 26 '22 at 11:57