Custom Spring Boot starters are valuable for encapsulating common functionalities, such as integrating with notification services like Feishu or DingTalk, or standardizing response code handling.
Project Setup
-
Initialize a Maven Project: Create a new Maven project, for instance, named
holmium-spring-boot-starter. -
Implement Core Functionality and Configuration:
-
Functionality Class: Define the core class that provides the desired functionality. For example, a
Userclass:package com.holmium.framwork.core; public class User { private String name; private int age; public User() { this.name = "xjh"; this.age = 18; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } } -
Auto-Configuration Class: Create a configuration class to automatically register beans when the starter is included. Use
@ConditionalOnClassto ensure the bean is created only if the specified class is present.package com.holmium.framwork.core; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class UserAutoConfiguration { @Bean @ConditionalOnClass(User.class) public User myUser() { return new User(); } }
-
-
Define
spring.factories: In thesrc/main/resourcesdirectory, create aMETA-INFfolder and in side it, aspring.factoriesfile. This file tells Spring Boot which auto-configuration classes to load.org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.holmium.framwork.core.UserAutoConfiguration -
Include Spring Boot Starter Dependency: Ensure your starter project includes the core Spring Boot starter dependency in its
pom.xml:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.6.13</version> </dependency> -
Incorporate the Starter into Another Project:
Add the custom starter as a dependency in the
pom.xmlof the project where you intend to use it. You can usually do this through your IDE by searching for the artifact.<dependency> <groupId>com.holmium</groupId> <artifactId>holmium-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> </dependency> -
Test the Integration:
Create a test case in your consuming project to verify that the beans provided by the starter are available and functioning correctly.
package com.example.demo; import com.holmium.framwork.core.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class CustomStarterIntegrationTest { @Autowired private User injectedUser; @Test void testStarterComponent() { System.out.println(injectedUser); // Add assertions here to verify user properties or behavior } }