Spring Data Jpa Bootstrap Mode

Spring Data Jpa uses a Repository interface to interact with the database. All Repository interface are by default Spring beans, it has singleton scoped and is eagerly initialized at the time of boot up.

At the time of boot up, the Spring Data Jpa Repository interface connects with JPA EntityManager and verify the database tables and metadata. Spring framework EntityManagerFactory initialization is a heave process and takes a considerable amount of time hence its move to a background thread. To make background initialization efficient and effective, JPA repositories must be initialized as late as possible.
Spring Data Jpa allows us to configure the EntityManagerFactory initialization process using @EnableJpaRepositories annotation.
Spring Data Jpa Bootstrap options are defined in enum BootstrapMode.

  • DEFAULT (default) — The Spring Data Jpa Repositories will instantiated eagerly unless explicitly annotated with @Lazy annotataion. The lazification only works if no other spring bean required this Reposotory bean, other wise it will initialized as per requirement.

  • LAZY — The Spring Data Jpa declares all repository beans to lazy initialization and injected into required beans. That means, that Spring Data Jpa Repositories will not be instantiated if there is no requirement of Repository during initialization. The Repository beans will be initialized and verified upon the very first call only. The application will fully start without the repositories initialized if there is no call during initialization.

  • DEFERRED —Deferred is almost same as LAZY, but when the container is done bootstrapping, it explicetly triggers repository initialization in response to an ContextRefreshedEvent so that repositories are verified before the application has completely started.

In order to check the optimization in server boot up time for each boot strap mode, here is an example with 2,000 entities, 2,000 repositories and 2,000 beans that depend on the repositories.

follow us on