Book Image

Spring Boot Cookbook

By : Alex Antonov
Book Image

Spring Boot Cookbook

By: Alex Antonov

Overview of this book

Table of Contents (15 chapters)
Spring Boot Cookbook
Credits
About the Author
Acknowledgment
About the Reviewers
www.PacktPub.com
Preface
Index

Configuring custom conditional bean instantiations


In the previous example, you learned how to get the basic Spring Boot Starter going. On the inclusion of the jar in the application classpath, the DbCountRunner bean will be created automatically and added to the application context. In the very first recipe of this chapter, we have also seen that Spring Boot has an ability to do conditional configurations depending on a few conditions, such as the presence of specific classes in the classpath, existence of a bean, and others.

For this recipe, we will enhance our starter with a conditional check. This will create the instance of DbCountRunner only if no other bean instance of this class has already been created and added to the application context.

How to do it…

  1. In the DbCountAutoConfiguration class, we will add an @ConditionalOnMissingBean annotation to the dbCountRunner(…) method, as follows:

    @Bean
    @ConditionalOnMissingBean
    public DbCountRunner dbCountRunner(Collection<CrudRepository&gt...