introduction
Spring Boot Starter is a core component of the Spring Boot ecosystem, which greatly simplifies the dependency management and configuration process of projects. Through the Starter mechanism, developers only need to introduce corresponding dependencies, and Spring Boot can automatically complete complex configuration work. For enterprise-level application development, we often need to reuse certain common functions in multiple projects, and it is particularly important to create a custom Starter.
1. Basic knowledge of custom Starter
Spring Boot Starter is essentially a collection of dependencies, combined with automatic configuration classes to provide an out-of-the-box experience for specific features. The core goal of custom Starter is to modularize reusable features, allowing other projects to use these features through simple dependencies.
A standard Spring Boot Starter usually consists of two main components: the automatic configuration module and the Starter module. The automatic configuration module contains specific implementation and configuration classes of functions, while the Starter module acts as an empty shell and only depends on the automatic configuration module and other necessary dependencies. This separate design enables functional implementation to be decoupled from dependency management, improving module flexibility.
Here are the basic naming specifications for custom Starter:
// For the official Starter, the naming format is:spring-boot-starter-{Function name} // For unofficial Starter, the naming format is:{Project name}-spring-boot-starter
The compliance of naming specifications helps distinguish between official and third-party Starters and avoid potential naming conflicts.
2. Create an automatic configuration module
The automatic configuration module is the core of Starter, which includes specific implementations of functions and automatic configuration classes.
Let’s take creating a simple data encryption Starter as an example to demonstrate the creation process of the automatic configuration module.
2.1 Project structure construction
First create a Maven project namedencryption-spring-boot-autoconfigure
, as an automatic configuration module.
The project structure is as follows:
encryption-spring-boot-autoconfigure/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/ │ │ │ └── example/ │ │ │ └── encryption/ │ │ │ ├── autoconfigure/ │ │ │ │ └── │ │ │ ├── properties/ │ │ │ │ └── │ │ │ └── service/ │ │ │ ├── │ │ │ └── impl/ │ │ │ └── │ │ └── resources/ │ │ └── META-INF/ │ │ └── └──
2.2 Configuring attribute classes
Create configuration properties classes to store and manage relevant configurations for encryption services:
package ; import ; /** * Encryption service configuration attribute class * Annotate the properties in the configuration file via @ConfigurationProperties annotation */ @ConfigurationProperties(prefix = "encryption") public class EncryptionProperties { /** * Encryption algorithm, default to AES */ private String algorithm = "AES"; /** * Encryption key */ private String key = "defaultKey123456"; /** * Whether to enable encryption service */ private boolean enabled = true; // Getter and Setter methods public String getAlgorithm() { return algorithm; } public void setAlgorithm(String algorithm) { = algorithm; } public String getKey() { return key; } public void setKey(String key) { = key; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { = enabled; } }
2.3 Service interface and implementation
Define the encryption service interface and its implementation:
package ; /** * Encryption service interface * Define basic operations of encryption and decryption */ public interface EncryptionService { /** * Encrypted string * * @param content content to be encrypted * @return Encrypted content */ String encrypt(String content); /** * Decrypt string * * @param encryptedContent Encrypted content * @return Decrypted original text */ String decrypt(String encryptedContent); }
AES encryption implementation class:
package ; import ; import ; import ; import ; import ; import .Base64; /** * AES encryption service implementation * Provide encryption and decryption functions based on AES algorithm */ public class AESEncryptionServiceImpl implements EncryptionService { private final EncryptionProperties properties; public AESEncryptionServiceImpl(EncryptionProperties properties) { = properties; } @Override public String encrypt(String content) { try { // Create key specification SecretKeySpec keySpec = new SecretKeySpec( ().getBytes(StandardCharsets.UTF_8), () ); // Get Cipher instance Cipher cipher = (()); // Initialize to encryption mode (Cipher.ENCRYPT_MODE, keySpec); // Execute encryption byte[] encrypted = ((StandardCharsets.UTF_8)); // Return the encryption result after Base64 encoding return ().encodeToString(encrypted); } catch (Exception e) { throw new RuntimeException("Encryption failed", e); } } @Override public String decrypt(String encryptedContent) { try { // Create key specification SecretKeySpec keySpec = new SecretKeySpec( ().getBytes(StandardCharsets.UTF_8), () ); // Get Cipher instance Cipher cipher = (()); // Initialize to decryption mode (Cipher.DECRYPT_MODE, keySpec); // Execute decryption byte[] original = (().decode(encryptedContent)); // Return to the decrypted original text return new String(original, StandardCharsets.UTF_8); } catch (Exception e) { throw new RuntimeException("Decryption failed", e); } } }
2.4 Automatic configuration class
Create an automatic configuration class and automatically assemble the encryption service according to the conditions:
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** * Automatic configuration class for encryption service * Responsible for automatically assembling encryption services according to conditions */ @Configuration @ConditionalOnClass() @EnableConfigurationProperties() @ConditionalOnProperty(prefix = "encryption", name = "enabled", havingValue = "true", matchIfMissing = true) public class EncryptionAutoConfiguration { /** * Register for encryption service Bean * When a bean of type EncryptionService does not exist in the container, create a default implementation */ @Bean @ConditionalOnMissingBean public EncryptionService encryptionService(EncryptionProperties properties) { return new AESEncryptionServiceImpl(properties); } }
2.5 File
existMETA-INF
Created in the directoryFile, specify the automatic configuration class:
# Automatic configuration class=\
2.6 Maven dependency configuration
File configuration:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="/POM/4.0.0" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0."> <modelVersion>4.0.0</modelVersion> <groupId></groupId> <artifactId>encryption-spring-boot-autoconfigure</artifactId> <version>1.0.0</version> <properties> <>11</> <>11</> <>2.7.0</> </properties> <dependencies> <!-- Spring Boot AutoConfigure --> <dependency> <groupId></groupId> <artifactId>spring-boot-autoconfigure</artifactId> <version>${}</version> </dependency> <!-- Used to generate configuration metadata --> <dependency> <groupId></groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>${}</version> <optional>true</optional> </dependency> </dependencies> </project>
3. Create Starter module
The Starter module is an empty shell module that relies on automatic configuration modules and other necessary dependencies to provide users with a one-stop dependency introduction experience.
3.1 Project Structure
Create a Maven project namedencryption-spring-boot-starter
, as Starter module:
encryption-spring-boot-starter/ └──
3.2 Maven dependency configuration
File configuration:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="/POM/4.0.0" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0."> <modelVersion>4.0.0</modelVersion> <groupId></groupId> <artifactId>encryption-spring-boot-starter</artifactId> <version>1.0.0</version> <properties> <>11</> <>11</> </properties> <dependencies> <!-- Rely on automatic configuration module --> <dependency> <groupId></groupId> <artifactId>encryption-spring-boot-autoconfigure</artifactId> <version>1.0.0</version> </dependency> <!-- Rely on other necessary libraries,Added according to functional requirements --> </dependencies> </project>
4. Use a custom Starter
Once created, we can use this custom Starter in other projects.
4.1 Add dependencies
On the projectAdd dependencies to:
<dependency> <groupId></groupId> <artifactId>encryption-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency>
4.2 Configuration Properties
existor
Configure encryption service properties in:
# Enable encryption service=true # Set up encryption algorithm=AES # Set the encryption key=mySecretKey12345
4.3 Use examples
Inject and use encryption services in business code:
package ; import ; import ; import ; import ; import ; /** * Encryption Service Demo Controller * Shows how to use the features provided by custom Starter in business code */ @RestController public class EncryptionController { private final EncryptionService encryptionService; @Autowired public EncryptionController(EncryptionService encryptionService) { = encryptionService; } @GetMapping("/encrypt") public String encrypt(@RequestParam String content) { return (content); } @GetMapping("/decrypt") public String decrypt(@RequestParam String content) { return (content); } }
5. Advanced Starter Features
5.1 Conditional configuration
Spring Boot provides rich conditional annotations to control the assembly conditions of the bean, making custom Starter more flexible:
// Take effect when a specified class exists under the classpath@ConditionalOnClass(name = "") // Take effect when the bean does not exist@ConditionalOnMissingBean // Take effect when the configuration property meets the conditions@ConditionalOnProperty(prefix = "feature", name = "enabled", havingValue = "true") // Take effect when the environment is a specified profile@ConditionalOnProfile("dev") // Take effect when the web application is Servlet type@ConditionalOnWebApplication(type = )
5.2 Automatic configuration sequence control
In complex scenarios, it may be necessary to control the execution order of multiple automatic configuration classes, which can be used@AutoConfigureBefore
and@AutoConfigureAfter
annotation:
//Execute before specifying the auto-configuration class@AutoConfigureBefore() // Execute after specifying the automatic configuration class@AutoConfigureAfter() // Sample code@Configuration @AutoConfigureAfter() public class EncryptionAutoConfiguration { // Configuration code}
5.3 Configuring Metadata
To provide better IDE support, configuration metadata files can be created:
{ "groups": [ { "name": "encryption", "type": "", "sourceType": "" } ], "properties": [ { "name": "", "type": "", "description": "Whether to enable encryption services", "sourceType": "", "defaultValue": true }, { "name": "", "type": "", "description": "Encryption algorithm", "sourceType": "", "defaultValue": "AES" }, { "name": "", "type": "", "description": "Encryption key", "sourceType": "", "defaultValue": "defaultKey123456" } ], "hints": [ { "name": "", "values": [ { "value": "AES", "description": "AES encryption algorithm" }, { "value": "DES", "description": "DES encryption algorithm" } ] } ] }
The configuration metadata file should be placed inMETA-INF/
Under the path, usually byspring-boot-configuration-processor
Automatically generated.
Summarize
Spring Boot Starter is a powerful automatic configuration mechanism. Through custom Starter, we can modularize common functions in our business and achieve high code reuse. The core of a custom Starter is to rationally design automatic configuration classes and configuration attribute classes, so that users can customize functional behavior through simple configurations.
During the creation process, we need to follow Spring Boot's naming specifications and best practices, separate the automatic configuration module from the Starter module, and improve flexibility. Through conditional configuration and automatic configuration sequence control, Starter can also work stably in complex scenarios.
For enterprise-level application development, custom Starter is a key tool to improve team efficiency. It not only simplifies project configuration, but also ensures that each project follows unified best practices and reduces maintenance costs.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.