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

What is the introduction and usage of Spring Boot Starter

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this issue, the editor will bring you a brief introduction and usage of Spring Boot Starter. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

The convenience of Spring Boot is reflected in that it simplifies a lot of tedious configuration, which is a boon for developers. By introducing various Spring Boot Starter packages, you can quickly build scaffolding for a project.

The Spring Boot Starter packages currently available are:

Spring-boot-starter-web: quickly build a Spring MVC-based Web project, using Tomcat as the default embedded container.

Spring-boot-starter-data-redis: manipulate Redis.

Spring-boot-starter-data-mongodb: manipulate Mongodb.

Spring-boot-starter-data-jpa: manipulate Mysql.

Spring-boot-starter-activemq: manipulate Activemq.

Automatic configuration is very convenient, when we want to operate Mongodb, we only need to introduce the dependency of spring-boot-starter-data-mongodb, and then configure the link information of Mongodb spring.data.mongodb.uri=mongodb://localhost/test to use MongoTemplate to manipulate the data, and all the initialization of MongoTemplate is left to Starter.

The trouble with automatic configuration is that when an error occurs, it becomes more difficult to troubleshoot. The logic of automatic configuration is in Spring Boot Starter, and if you want to quickly locate the problem, you must understand the internal principles of Spring Boot Starter. Next, let's implement a Spring Boot Starter ourselves.

Spring Boot Starter project creation

Create a project spring-boot-starter-demo,pom.xml configuration code as shown below.

Org.springframework.bootspring-boot-starter-weborg.projectlomboklomboktrue

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

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

Then define a Client, which is equivalent to MongoTemplate, and specify a method to get the value 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 ();}} automatically create a client

A basic Starter package is defined, but you certainly can't use UserClient at this time, because we don't have an instance of UserClient built automatically. Next, start building the 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);}}

Spring Boot scans packages at the same level as the startup class by default. If our Starter is not under the same main package as the startup class, how can we make UserAutoConfigure take effect?

Create a META-INF folder under resources, and then create a spring.factories file in the META-INF folder that specifies the automatically configured classes:

Org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.cxytiandi.demo.UserAutoConfigure

When Spring Boot starts, it reads the spring.factories file, and then activates the corresponding configuration class according to the configuration. At this point, a simple Starter package is implemented.

Use Starter

You can now introduce this Starter package into other projects, as shown below.

Com.cxytiandispring-boot-starter-demo0.0.1-SNAPSHOT

After introduction, you can directly use UserClient,UserClient to initialize the project automatically when it starts, as shown in the code below.

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

Spring.user.name=zhangsanspring.user.enabled=true

Visit / user/name to return the zhangsan we configured.

Use annotations to turn on Starter automatic build

In many cases, we do not want to perform the initialization logic when the Starter package is introduced, but we want the user to specify whether to enable the autoconfiguration function of the Starter package. For example, the commonly used annotation @ EnableAsync is used to enable the function of calling method execution asynchronously.

Similarly, we can also use annotations to enable autoconfiguration. If annotations are used, then spring.factories does not need to be written. Let's take a look at how to define annotations that enable autoconfiguration, as shown below.

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

The core of this code is @ Import ({UserAutoConfigure.class}), which adds the UserAutoConfigure instance to the SpringIOC container by import, so that automatic configuration can be turned on.

The way to use it is to add this comment to the startup class, as shown in the following code.

@ SpringBootApplicationpublic class SpringBootDemoApplication {public static void main (String [] args) {SpringApplication.run (SpringBootDemoApplication.class, args);}} enable Starter automatic build with configuration

In some scenarios, multiple objects will be configured in UserAutoConfigure. If you do not want to configure all of these objects, or if you want the user to specify whether to build objects when the configuration needs to be enabled, we can use @ ConditionalOnProperty to specify whether to enable the configuration feature. The code is as follows.

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

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

Configure Starter content prompts

In the process of customizing the Starter package, it is also important to prompt for the configured content items. It should be noted that prompts are not supported in Eclipse, but can be prompted in Spring Tools 4 for Eclipse.

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}]}

Name: configuration name

Type: configured data type

DefaultValue: default

The above is the brief introduction and usage of Spring Boot Starter shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

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