Once upon a time, an interviewer asked me about the development process of a SpringBoot Starter. I said THAT I had never written a Starter, and then I didn’t. The interviewer told me that I didn’t have enough technical depth.

I want to say that this thing is not very simple, if you have to write one is also a matter of minutes. As for thinking I don’t know SpringBoot at all because I haven’t written starter?

Of course, I was really not good enough at that time, and even forgot what the SPI of Java was. Later, I picked it up again. I had used the SPI of Java when I was in college.

What is a SpringBoot starter

Starter is an important component of SpringBoot. It acts as an integrated module. For example, if you want to use Mybatis and Lombok, you need to write two dependencies in the POM file. If you integrate them as a starter (or as many dependencies as you need), then you only need to write one starter dependency in the POM file, which is great for the development and maintenance of a reusable module.

Also, with the introduction of the starter dependency in Maven, SpringBoot automatically scans for information to load and starts the corresponding default configuration, following the “convention over configuration” philosophy.

How to develop a SpringBoot starter

1. Environment description

The JDK 1.8.0 comes with _151

Maven 3.6.3

The IDEA of a compiler

Starter is a date formatting tool that specifies how to format and convert date types, and can be turned on or off in the configuration file

2. Create projects

Create a New Maven project in IDEA, as shown below.

Spring officially recommends that a customized starter use the xxX-spring-boot-starter naming rule to distinguish the starter provided by the SpringBoot ecology.

You then need to add the dependencies needed to implement starter into the POM file.

<? The XML version = "1.0" encoding = "utf-8"? > < project XMLNS = "http://maven.apache.org/POM/4.0.0" XMLNS: xsi = "http://www.w3.org/2001/XMLSchema-instance" Xsi: schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < groupId > org. Walker. Planes < / groupId > < artifactId > date format - spring - the boot - starter < / artifactId > < version > 1.0 - the SNAPSHOT < / version > < dependencies > < the dependency > <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> < version > 2.3.0. RELEASE < / version > < / dependency > < / dependencies > < project >Copy the code

3. Create the configuration information entity class

When developing SpringBoot projects, we sometimes make configuration changes in the application.properties configuration file to enable or modify related configurations. For example, server.port can be used to change the port on which the project is launched. So when writing a custom date-formatting starter, you can also use this feature to turn something on or off based on the configuration file.

We added two new configuration items to the application.properties configuration file. The first is to control whether the starter is turned on or off, and the second is the formatting information to specify.

Then create a configuration file mapping class whose private member variable pattern is the attribute that needs to be specified in the configuration file. If not specified, the default value is YYYY-MM-DD HH: MM :ss.

import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author Planeswalker23 * @date 2020-05-25 */ @configurationProperties ("formatter") public class DateFormatProperties { /** * default format pattern */ private String pattern = "yyyy-MM-dd HH:mm:ss"; // Ignore the getter setter}Copy the code

The @ConfigurationProperties(prefix = “formatter”) annotation maps configuration information of the same prefix to an entity class through the configuration item name. This is where configuration items with a Formatter prefix in the Application.properties configuration file can be mapped to the DateFormatProperties class.

4. Create a configuration class

We then need to create a configuration class that can inject the core functionality classes into the Ioc container to make the auto-configured functionality available in other projects that reference the starter.

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.text.SimpleDateFormat; /** * Configuration information entity class * @author Planeswalker23 * @date 2020-05-25 */ @configuration @EnableConfigurationProperties(DateFormatProperties.class) @ConditionalOnProperty(prefix = "formatter", name = "enabled", havingValue = "true") public class DateFormatConfiguration { private DateFormatProperties dateFormatProperties; public DateFormatConfiguration(DateFormatProperties dateFormatProperties) { this.dateFormatProperties = dateFormatProperties; } @Bean(name = "myDateFormatter") public SimpleDateFormat myDateFormatter() { System.out.println("start to initialize SimpleDateFormat with pattern: " + dateFormatProperties.getPattern()); return new SimpleDateFormat(dateFormatProperties.getPattern()); }}Copy the code

The starter function is based on the SimpleDateFormat class. In fact, it parses the specified format in the configuration file and sets it to the Pattern property of SimpleDateFormat. Then register the SimpleDateFormat class as a “component” in the Ioc container so that we can use custom formatting capabilities in projects that reference the Starter.

The @Configuration annotation is used to inject the DateFormatConfiguration class into the container as a Configuration class

@ EnableConfigurationProperties annotation is the function of open resources entity class loading, that is open for the resource configuration file mapping the function of the entity class.

ConditionalOnProperty the @conditionalonProperty annotation enables conditional configuration, meaning that the starter will only take effect if the formatter.enabled property in the configuration file has a value of true.

5. Specify automatic assembly

This is the end of the business code developed, but the most important step is to specify the DateFormatConfiguration class as the autowage class.

To do this, you need to create a mate-INF folder in the resource directory and create a file called Spring.Factories in that file

org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.walker.planes.DateFormatConfigurationCopy the code

The DateFormatConfiguration is set to auto-assembly classes. When the SpringBoot project starts, it scans the Spring. factories file in the mate-INF folder and loads the specified classes. Enable automatic assembly.

6. Release & Test

Then type the MVN clean install command from the command line, and when you see the output below, the custom starter can be referenced as a dependency.

[INFO] ----------------------------------------------------------- [INFO] BUILD SUCCESS [INFO] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [INFO] Total time: 1.470 s [INFO] Finished at: 2020-05-25T20:24:49+08:00 [INFO] -----------------------------------------------------------Copy the code

Create a new test project and add the following dependencies to the POM file.

<dependency> <groupId>org.walker.planes</groupId> <artifactId>date-format-spring-boot-starter</artifactId> < version > 1.0 - the SNAPSHOT < / version > < / dependency >Copy the code

Then enable the configuration of the custom starter in the application.properties file. Formatter. enabled=true formatter.pattern= YYYY-MM-DD Then creates a Runner task in the boot class that simply outputs a date class, as shown below.

@SpringBootApplication public class FirstStarterApplication implements ApplicationRunner { public static void main(String[] args) { SpringApplication.run(FirstStarterApplication.class, args); } @Override public void run(ApplicationArguments args) throws Exception { System.out.println(simpleDateFormat.format(new  Date())); } @Resource(type = SimpleDateFormat.class) private SimpleDateFormat simpleDateFormat; }Copy the code

After starting the project, we can see that the autoconfiguration takes effect. The application overwrites the default pattern with the formatting style specified in the configuration file.

. ____ _ __ _ _ / \ \ / ___ '_ __ _ _) (_ _ __ __ _ \ \ \ \ (\ ___ () |' _ | '_ | |' _ \ / _ ` | \ \ \ \ \ \ / ___) | | _) | | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.0. RELEASE) the 2020-05-25 20:31:27. 144 INFO 5559 - [the main] org. Test. FirstStarterApplication: Starting FirstStarterApplication on fandeMac-mini.local with PID 5559 (/Users/fan/workspace/first-starter/target/classes Started by fan in/Users/fan/workspace/first - starter) 20:31:27 2020-05-25. 5559-146 the INFO [main] org.test.FirstStarterApplication : No active profile set, falling back to default profiles: default start to initialize SimpleDateFormat with pattern: MM - dd yyyy - 2020-05-25 20:31:27. 792 INFO 5559 - [the main] org. Test. FirstStarterApplication: Started FirstStarterApplication in 0.894 seconds (JVM running for 1.4) 2020-05-25Copy the code

Now that we’ve completed a simple SpringBoot Start development, we’ll conclude with a starter development process.

  • Introduce the spring-boot-autoconfigure dependency
  • Create the configuration entity class
  • Create the auto-configuration class, set the instantiation condition (annotated by @conditionalxxx, optional), and inject the container
  • Enable automatic configuration by creating a spring.factories folder in the mate-INF folder.
  • Publish the starter in the Maven repository

Original link:

juejin.cn/post/1

Wenyuan network, only for the use of learning, if there is infringement please contact delete.

I’ve compiled the interview questions and answers in PDF files, as well as a set of learning materials covering, but not limited to, the Java Virtual Machine, the Spring framework, Java threads, data structures, design patterns and more.

Follow the public account “Java Circle” for information, as well as quality articles delivered daily.