DEV Community

eidher
eidher

Posted on • Updated on

Lazy Beans in Spring

Beans are created on startup when the application context is created (eagerly). But, lazy beans are created the first time they are used. Its use is not recommended.

@Lazy
@Component("jdbcRepository")
public class JdbcRepositoryImpl implements AppRepository {
    ...
}
Enter fullscreen mode Exit fullscreen mode

When we put the @Lazy annotation over the @Configuration class, all the methods with @Bean annotation should be loaded lazily.

Top comments (2)

Collapse
 
kriska profile image
Kristina Gocheva

You've described very briefly the lazy annotation and its effect. I would like to understand why you said that it's usages is not recommended. Some additional examples would be helpful.

Collapse
 
eidher profile image
eidher

I won't recommend its use because we could mask issues, getting them in run time instead of startup time (out of memory errors, misconfigurations, or class-definition-found errors). Besides, triggering bean creation on demand will increase the latency of HTTP requests impacting load balancing and autoscale in cloud environments.