Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize Standard Spring Boot starter

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to customize the standard Spring Boot starter". In the daily operation, I believe that many people have doubts about how to customize the standard Spring Boot starter. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to customize the standard Spring Boot starter"! Next, please follow the editor to study!

Custom starter

Before we delve into how to customize starter, in order to better understand what we are doing at each step and how starter works, let's look at the structure of starter from a macro point of view.

Typically, a complete starter needs to include the following two components:

Auto-Configure Module

Starter Module

If you look at the following two components of the interpretation of some abstract, probably understand, after reading this article will suddenly be enlightened here

Auto-Configure Module

Auto-Configure Module (autoconfiguration module) is a Maven or Gradle module that contains autoconfiguration classes. In this way, we can build modules that automatically contribute to the application context, add a feature or provide access to an external library

Starter Module

Spring Boot Starter is a Maven or Gradle module whose sole purpose is to provide all the dependencies needed to "start" a feature. Can contain one or more Auto-Configure Module (autoconfiguration module) dependencies, as well as any other dependencies that may be needed. In this way, in the Spring startup application, we only need to add this starter dependency to use its features

The Spring official reference manual recommends separating autoconfiguration and launching each autoconfiguration into a separate Maven or Gradle module, thus separating autoconfiguration from dependency management If you don't have an open source library for thousands of users, you can combine the two into one module

You may combine the auto-configuration code and the dependency management in a single module if you do not need to separate those two concerns

Naming

Official starter from Spring starts with spring-boot-starter, such as:

Spring-boot-starter-web

Spring-boot-starter-aop

If we customize the name of the starter feature as acme, then our name looks like this:

Acme-spring-boot-starter

Acme-spring-boot-autoconfigure

If configuration keys is used in starter, be careful not to use the namespace used by Spring Boot, such as (server,management,spring)

Parent Module creation

Let's take a look at the project structure as a whole:

First-level directory structure:.

├── pom.xml ├── rgyb-spring-boot-autoconfigure ├── rgyb-spring-boot-sample └── rgyb-spring-boot-starter

Secondary directory structure:.

├── pom.xml ├── rgyb-spring-boot-autoconfigure │ ├── pom.xml │ └── src ├── rgyb-spring-boot-sample │ ├── pom.xml │ └── src └── rgyb-spring-boot-starter ├── pom.xml └── src

Create an empty parent Maven Module, which mainly provides dependency management, so that SubModule does not have to maintain the dependent version number separately. Take a look at the pom.xml content:

Org.springframework.boot spring-boot-dependencies ${spring-boot.version} pom import

Auto-Configure Module construction

Create a new class GreetingAutoConfiguration

Configuration public class GreetingAutoConfiguration {@ Bean public GreetingService greetingService (GreetingProperties greetingProperties) {return new GreetingService (greetingProperties.getMembers ());}}

We mark the class GreetingAutoConfiguration with the @ Configuration annotation as the entry point for starter. This configuration contains all the @ Bean definitions that we need to provide the starter feature, and in this case, to briefly illustrate the problem, we just add GreetingService Bean to the application context

The GreetingService content is as follows:

@ AllArgsConstructor public class GreetingService {private List members = new ArrayList (); public void sayHello () {members.forEach (s-> System.out.println ("hello" + s));}}

Create a new file META-INF/spring.factories under the resources directory (if the directory META-INF does not exist, you need to create it manually), and write to the file:

Org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ top.dayarch.autoconfigure.GreetingAutoConfiguration

When Spring starts, it will load all the spring.factoreis files in its classpath and load the declared configuration inside. When the GreetingAutoConfiguration class is ready, our Spring Boot Starter will have an entry point for automatic activation.

At this point, this "incomplete starter" is ready to use. But because it is activated automatically, in order to make it flexible, we need to activate it according to our wishes, so we need conditional comments to help.

Conditional configuration

Add two conditional comments to the class:

@ Configuration @ ConditionalOnProperty (value = "rgyb.greeting.enable", havingValue = "true") @ ConditionalOnClass (DummyEmail.class) public class GreetingAutoConfiguration {...}

By using the @ ConditionalOnProperty annotation, we tell Spring that GreetingAutoConfiguration (and all bean it declares) is included in the application context only if the property rgyb.greeting.enable value is set to true

By using the @ ConditionalOnClass annotation, we tell Spring that GreetingAutoConfiguration (and all bean it declares) is included in the application context only if the class DummyEmail.class exists in classpath

Multiple conditions are the relationship between and/ and GreetingAutoConfiguration, and GreetingAutoConfiguration will be loaded only if all the conditions are met.

If you are not clear about the use of conditional annotations, you can check out my previous article: @ Conditional annotations, flexible configuration of Spring Boot

Configure attribute management

Using the @ ConditionalOnProperty annotation above, there may be a lot of attributes in the actual starter, so we need to manage these attributes centrally:

@ Data @ ConfigurationProperties (prefix = "rgyb.greeting") public class GreetingProperties {/ * GreetingProperties switch * / boolean enable = false; / * list of members to greet * / List members = new ArrayList ();}

We know that these attributes are to be used in application.yml, and when we need to use them, in order for IDE to give a more friendly hint, we need to add dependencies to pom.xml:

Org.springframework.boot spring-boot-configuration-processor true

In this way, when we mvn compile, we will generate a file called spring-configuration-metadata.json JSON with the following contents:

The generated content is used in the following content, and see

Increase start-up time

For each autoconfiguration class on the classpath, Spring Boot must calculate @ Conditional... Conditional value, which is used to determine whether to load the automatic configuration and all its required classes, which can be a very expensive operation and affect the startup time, depending on the size and number of starter in the Spring startup application. In order to improve the startup time, we need to add another dependency to pom.xml:

Org.springframework.boot spring-boot-autoconfigure-processor true

This annotation generates a file called spring-autoconfigure-metadata.properties Property, which reads as follows:

In this way, Spring Boot reads the metadata during startup and can filter out configurations that do not meet the criteria without having to actually check these classes to speed up startup

At this point, the construction of Auto-Configure Module is done, and we need to continue to build Starter Module.

Starter Module construction

The construction of Starter Module is very simple. You can think of it as an empty module. In addition to relying on Auto-Configure Module, its only function is to provide all necessary dependencies in order to use starter features, so we add the following to starter module's pom.xml file:

Top.dayarch.learnings rgyb-spring-boot-autoconfigure 1.0.0.RELEASE

Also create a new file META-INF/spring.providers under the resources directory with the following contents:

Providers: rgyb-spring-boot-autoconfigure

The main purpose of this file is to explain the dependency information of starter module. As long as multiple dependencies are separated by commas, the file will not affect the use of starter.

Starter Module can be as simple as mvn install the two module to the local Maven Repository, and then when we create sample module to introduce this starter dependency, we will pull it from the local Maven Repository.

Create Sample Module

We can initialize a Spring Boot project (rgyb-spring-boot-sample) normally through Spring Initializr, introduce the starter dependency we just created, and add the dependency to sample pom.xml:

Top.dayarch.learnings rgyb-spring-boot-starter 1.0.0.RELEASE

Next, configure the application.yml property

Rgyb: greeting: enable: true members:-Li Lei-Han Meimei

When we configure YAML, the following prompt appears, which will be more friendly. Of course, for the sake of specification, the attribute description should also be described in English. Here, the Chinese description is used to illustrate the problem:

Write test classes

We write test cases:

Autowired (required = false) private GreetingService greetingService; @ Test public void testGreeting () {greetingService.sayHello ();}

The test results are as follows:

Hello Li Lei hello Han Meimei

Knowledge point explanation

Dependency optinal

Why is the dependency of Auto-Configure Module always optional = true?

This involves the issue of Maven transitive dependency. For more information, please see Maven dependency transitivity thorough understanding.

Spring.factories

How Spring Boot loads this file and finds our configuration class

The following figure is part of the call stack started by the Spring Boot application, and I added breakpoints:

Open the SpringFactoriesLoader class and this is what you see:

These two pictures should be enough to illustrate the problem. It is a way to load SPI. Please find out the details for yourself.

At this point, the study on "how to customize the standard Spring Boot starter" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report