Create a Custom Spring Boot Starter to Auto‑Count Database Entities

This guide explains how to build a Spring Boot starter that automatically counts and logs the number of entries for each entity at application startup, covering starter concepts, Maven setup, code implementation, auto‑configuration, and integration into a main project.

Programmer DD
Programmer DD
Programmer DD
Create a Custom Spring Boot Starter to Auto‑Count Database Entities

What is a Spring Boot starter?

In Spring Boot, a starter is a convenient dependency bundle that hides the underlying libraries and configuration, allowing developers to use a feature without worrying about classpath details. For example, spring-boot-starter-jdbc lets you autowire a DataSource bean with a single annotation.

Goal of this tutorial

We will create a custom starter named db-count-starter that, after the application starts, prints the number of records for each JPA entity.

1. Create the starter module

Add a new Maven module db-count-starter and modify its pom.xml to include the required dependencies:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot</artifactId>
        <!-- version inherited from parent -->
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
        <version>1.9.3.RELEASE</version>
    </dependency>
</dependencies>

2. Implement the runner

Create the package com.test.bookpubstarter.dbcount and add DbCountRunner that implements CommandLineRunner:

package com.test.bookpubstarter.dbcount;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.repository.CrudRepository;
import java.util.Collection;

public class DbCountRunner implements CommandLineRunner {
    protected final Logger logger = LoggerFactory.getLogger(DbCountRunner.class);
    private Collection<CrudRepository> repositories;

    public DbCountRunner(Collection<CrudRepository> repositories) {
        this.repositories = repositories;
    }

    @Override
    public void run(String... strings) throws Exception {
        repositories.forEach(crudRepository -> {
            logger.info(String.format("%s has %s entries",
                getRepositoryName(crudRepository.getClass()),
                crudRepository.count()));
        });
    }

    private static String getRepositoryName(Class crudRepositoryClass) {
        for (Class repositoryInterface : crudRepositoryClass.getInterfaces()) {
            if (repositoryInterface.getName().startsWith("com.test.bookpub.repository")) {
                return repositoryInterface.getSimpleName();
            }
        }
        return "UnknownRepository";
    }
}

3. Add auto‑configuration

Create DbCountAutoConfiguration to expose the runner as a bean:

package com.test.bookpubstarter.dbcount;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.CrudRepository;
import java.util.Collection;

@Configuration
public class DbCountAutoConfiguration {

    @Bean
    public DbCountRunner dbCountRunner(Collection<CrudRepository> repositories) {
        return new DbCountRunner(repositories);
    }
}

4. Register the auto‑configuration

Under src/main/resources/META-INF create spring.factories with the following line:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.test.bookpubstarter.dbcount.DbCountAutoConfiguration

5. Use the starter in a main project

Add the starter as a dependency in the parent pom.xml:

<dependency>
    <groupId>com.test</groupId>
    <artifactId>db-count-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

Run the main application (e.g., BookPubApplication.main(...)) and observe that the starter logs the entity counts.

Analysis

A proper starter is an independent project published to a Maven repository so other developers can reuse it. Typical components include:

Auto‑configuration classes that are conditionally applied based on classpath. spring.factories to let Spring Boot discover the auto‑configuration.

Optional endpoints for admin UI and health indicators.

During startup, Spring Boot uses SpringFactoriesLoader to scan META-INF/spring.factories files across all JARs, building a list of configuration classes. It also supports other extension points such as ApplicationContextInitializer, ApplicationListener, and more.

Two important points

@ConditionalOnMissingBean

ensures that the auto‑configuration runs only when the user has not defined a bean of the same type, giving precedence to manually created beans.

The starter finds its auto‑configuration via the spring.factories entry; sometimes an @Enable annotation is needed to trigger the discovery.

By following these steps you can package reusable functionality as a Spring Boot starter and integrate it seamlessly into any Spring Boot application.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

mavenSpring BootStarterCommandLineRunner
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.