Card 05/ 06

ExerciseDifficulty: Advanced1 min

Practice: Predicting What Auto-Configuration Creates

Three setups, three answers, each decided by a condition you can name.

Auto-configuration creates a bean only when its conditions hold, mostly @ConditionalOnClass (a library is on the classpath) and @ConditionalOnMissingBean (you have not defined that bean yourself). For each setup below, say whether Boot creates the bean, and which condition decides it.

  1. spring-boot-starter-data-jpa (the dependency that brings in JPA and Hibernate) is on the classpath, and you have defined your own EntityManagerFactory bean.
  2. spring-boot-starter-cache is on the classpath, you have added @EnableCaching yourself, and no cache library such as Caffeine is present.
  3. Nothing web-related is on the classpath at all, and your main class is annotated @SpringBootApplication.
See the answers
  1. No. @ConditionalOnMissingBean sees your EntityManagerFactory and backs off, exactly as it does for a DataSource you define yourself.
  2. Yes, a simple one. With no cache library on the classpath, Boot falls back to its own basic cache backed by a ConcurrentHashMap. The @ConditionalOnClass check for Caffeine fails, but caching itself was still switched on.
  3. No web server and no DispatcherServlet, the component that routes each web request to a controller. @ConditionalOnClass looks for Spring MVC and an embedded server; neither is on the classpath, so none of the web auto-configuration activates.