0

There are many examples and documentations about @Lazy. Maybe I didn't get the point, but why should it ever be used? Instantiating a bean costs < 1 ms at startup. Using lazy loading for beans gives you a bunch of new integration tests. Furthermore it could be rather dangerous, when your application starts up with no errors and crashes on the first call to a lazy loaded bean. So why? Does anybody has got a good example?

El Gohr
  • 177
  • 1
  • 12
  • Instantiating a bean costs < 1ms if the constructor (and the post-construct hooks) don't have much to do. But they might take much longer. Imagine a bean reading many files at startup, or connecting to a slow and rarely used external service. Loading eagerly by default is what you want most of the time, and it's a safer default, but that doesn't mean lazy can't be useful. – JB Nizet Apr 15 '17 at 23:02
  • Read this answer http://stackoverflow.com/questions/26611173/jpa-jta-transactional-spring-annotation/26615390#26615390 – Harshal Patil Apr 16 '17 at 14:34
  • Don't get the link to the other article – El Gohr Apr 16 '17 at 15:16

1 Answers1

0

Lazy initialization might be useful, when your @Lazy annotated component depends on some infrastructure to be properly initialized. So, for example, if you have a component which needs to download some files during startup, then it probably makes a lot of sense to annotate it with @Lazy. This way it doesn't try to download files (which takes a lot of time) when it's not going to be used for a while.

However, personally I think using lazy components often leads to a bad design. Think twice before you use it.

Mike Wojtyna
  • 751
  • 5
  • 10
  • I don't know if I would use it in this scenario. Looking at Spring Boot Config Server (which is such a long run scenario) this could be deadly. I was thinking about scenarios, where the beans are not in Singleton scope. Let's say we got a statefull service, which is only called sometimes. Could this be a way to avoid unnecessary allocation of resources? – El Gohr Apr 16 '17 at 14:46
  • Well, in such case a simple factory is the way to go. Just ignore lazy loading and create a factory that will build instances of your service in the runtime. Thanks to factory you instantiate your services only when you really need it. – Mike Wojtyna Apr 16 '17 at 19:34