This article has participated in the call for good writing activities, click to view: back end, big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!

directory

The Spring Boot Starter project is created

Automatically create clients

Use the Starter

Use annotations to turn on the Starter autobuild

Enable the Starter automatic build using the configuration

Configure the Starter prompt

The convenience of Spring Boot is that it simplifies a lot of cumbersome configuration, which is a boon for developers. By introducing various Spring Boot Starter packages, you can quickly scaffolding a project. The current Spring Boot Starter packages are:

  • Spring-boot-starter-web: Quickly build web projects based on Spring MVC, using Tomcat as the default embedded container.
  • Spring-boot-starter-data-redis: operates redis.
  • Spring-boot-starter-data-mongodb: operates mongodb.
  • Spring-boot-starter-data-jpa: operates Mysql.
  • Spring-boot-starter – ActivemQ: Operates activemQ.

Automatic configuration is very convenient. When we need to operate Mongodb, we only need to introduce the spring-boot-starter-data-mongodb dependency. = spring.data.mongodb.uri= Mongodb: //localhost/test can then use MongoTemplate to manipulate data, leaving all initialization of the MongoTemplate to the Starter. The trouble with auto-configuration is that it makes it harder to troubleshoot problems when something goes wrong. The automatic configuration logic is in the Spring Boot Starter. To quickly locate problems, you must understand the internal principles of the Spring Boot Starter. Let’s implement a Spring Boot Starter ourselves.

The Spring Boot Starter project is created

Create a project spring-boot-starter-demo with the pom.xml configuration code shown below.

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>Copy the code

Create a configuration class to configure values in the properties file, in the form of spring.data.mongo, as shown below.

Copy the code
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
@Data
@ConfigurationProperties("spring.user")
public class UserPorperties {
    private String name;
}
Copy the code

Define a Client, equivalent to MongoTemplate, with a method to get the values in the configuration, as shown below.

public class UserClient { private UserPorperties userPorperties; public UserClient() { } public UserClient(UserPorperties p) { this.userPorperties = p; } public String getName() { return userPorperties.getName(); }}Copy the code

Automatically create clients

A basic Starter package is defined, but UserClient is definitely not available at the moment, since we don’t automatically build instances of UserClient. Start building UserClient with the code shown below.

@Configuration @EnableConfigurationProperties(UserPorperties.class) public class UserAutoConfigure { @Bean @ConditionalOnProperty(prefix = "spring.user", value = "enabled", havingValue = "true") public UserClient userClient(UserPorperties userPorperties) { return new UserClient(userPorperties); }}Copy the code

By default, Spring Boot scans for packages that are at the same level as the Starter class. If the Starter class and our Starter class are not in the same main package, how can UserAutoConfigure take effect? Under Resources, create a meta-INF folder and in the Meta-INF folder create a Spring. factories file specifying the auto-configured classes:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.cxytiandi.demo.UserAutoConfigure
Copy the code

Spring Boot reads the Spring.Factories file when it starts, and then activates the corresponding configuration classes according to the configuration, so that a simple Starter package is implemented.

Use the Starter

You can now introduce the Starter package in other projects, as shown below.

<dependency> <groupId>com.cxytiandi</groupId> <artifactId>spring-boot-starter-demo</artifactId> < version > 0.0.1 - the SNAPSHOT < / version > < / dependency >Copy the code

Once introduced, you can use UserClient directly, which is automatically initialized when the project starts, as shown below.

@RestController public class UserController { @Autowired private UserClient userClient; @GetMapping("/user/name") public String getUserName() { return userClient.getName(); }}Copy the code

Configure the value of name in the properties file and enable UserClient:

spring.user.name=zhangsan
spring.user.enabled=true
Copy the code

Calling /user/name returns our configured Zhangsan.

Use annotations to turn on the Starter autobuild

Most of the time, we do not want to perform the initialization logic when the Starter package is introduced. Instead, we want the user to specify whether to enable the automatic configuration function of the Starter package. For example, the @enableAsync annotation is used to enable the asynchronous execution of the calling method. In the same way, you can use annotations to enable or disable auto-configuration. If you use annotations, then spring.factories don’t need to be written.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({UserAutoConfigure.class})
public @interface EnableUserClient {

}
Copy the code

The core of this code is @import ({userAutoconfigure.class}), which implements the Import of the UserAutoConfigure instance into the SpringIOC container, thus enabling automatic configuration. This is done by adding the annotation to the startup class, as shown below.

@SpringBootApplication public class SpringBootDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDemoApplication.class, args); }}Copy the code

Enable the Starter automatic build using the configuration

In some cases, UserAutoConfigure configures multiple objects. For these objects, if you don’t want to configure them all, or if you want the user to specify when the configuration needs to be enabled, build the object. You can specify whether to enable the configuration function by calling @conditionalonProperty, as shown below.


@Bean
@ConditionalOnProperty(prefix = "spring.user",value = "enabled",havingValue = "true")
public UserClient userClient(UserPorperties userPorperties) {
return new UserClient(userPorperties);
}
Copy the code

With the above configuration, UserClient is automatically configured only if @enableUserClient is added to the startup class and spring.user.enabled=true in the configuration file.

Configure the Starter prompt

In the process of customizing the Starter package, it is important to provide tooltips for the configured content items. Note that tooltips are not supported in Eclipse. Spring Tools 4 for Eclipse provides tooltips. To define the prompt content, you need to create a spring-configuration-metadata.json file in meta-INF, as shown below.

{ "properties": [ { "name": "spring.user.name", "defaultValue": "cxytinadi" }, { "name": "spring.user.enabled", "type": "java.lang.Boolean", "defaultValue": false } ] }
Copy the code
  • Name: indicates the configuration name
  • Type: indicates the configured data type
  • DefaultValue: indicates the defaultValue

Spring Boot Project construction steps (super detailed)

What is Spring Cloud Eureka

Relevant Springboot actual combat project recommendation

Based on Java SSM Springboot +VUE epidemic prevention system system front and back end separation design and implementation

Based on Java Springboot + Mybatis film ticket website management system front + background design and implementation

Design and implementation of winery internal management system based on Java SSM Springboot + Mybatis

Design and implementation of intelligent life sharing platform based on JAVA Springboot + Mybatis

Based on Java Springboot + VUE + Redis front and back end separation furniture mall platform system design and implementation

Design and implementation of anti-epidemic material information management system based on JAVA SSM Springboot

>>>