Table of Contents
What is Spring Boot Starter?
Previous traditional approach
After using Spring Boot Starter
The concept of starter:
Implementation of starter:
Create Spring Boot Starter steps
Specific steps:
Create the business class:
测试如下:
Home Java javaTutorial SpringCloud-Spring Boot Starter usage test instance analysis

SpringCloud-Spring Boot Starter usage test instance analysis

May 16, 2023 am 11:10 AM
springboot springcloud starter

What is Spring Boot Starter?

Spring Boot Starter is a concept proposed in the SpringBoot component, which simplifies many cumbersome configurations. By introducing various Spring Boot Starter packages, you can quickly build the scaffolding of a project.

For example, some of the ones we often use:

spring-boot-starter-web:

spring-boot-starter-data-redis:

spring-boot-starter-data-mongodb:

spring-boot-starter-data-jpa:

spring-boot-starter-activemq:

In general, starter is a synthesis of dependencies.

Previous traditional approach

Before there was no starter, for traditional SSM projects, if I wanted to use jpa in Spring, I might need to do the following:

First of all, Introduce the dependencies of the database used in Maven>>Then introduce the dependencies of jpa>>Configure some attribute information in xml>>Debug the call until it can run normally.

The above operation will have some problems, such as:

If the process is complicated, such step-by-step operation will increase the possibility of errors.

It also takes a lot of time during configuration, and is not very friendly to novices and novices.

After using Spring Boot Starter

The main purpose of starter is to solve the above problems

The concept of starter:

starter will use all All dependencies are included, avoiding the trouble caused by developers themselves introducing dependencies. It should be noted that different starters are designed to solve different dependencies, so their internal implementations may be very different. For example, the starter of jpa and the starter of Redis may have different implementations. This is because the essence of starter lies in synthesissize. This is a layer of abstraction at the logical level. Maybe this concept is somewhat similar to Docker, because they are both doing a "packaging" operation. If you know what problem Docker is to solve, maybe you can use Docker and starter Make an analogy.

Implementation of starter:

Although different starters have different implementations, they basically use the same two things: ConfigurationProperties and AutoConfiguration. Because Spring Boot firmly believes in the concept of "convention over configuration", we use ConfigurationProperties to save our configurations, and these configurations can have a default value, that is, if we do not actively overwrite the original configuration, the default value will takes effect, which is very useful in many situations. In addition, the starter's ConfigurationProperties also allows all configuration properties to be gathered into one file (usually application.properties in the resources directory), so we say goodbye to the XML hell in the Spring project.

SpringCloud-Spring Boot Starter usage test instance analysis

The jar that the above starter relies on is no different from the jar that we rely on when configuring it manually, so we can think that the starter actually handles these tedious configuration operations. Leave it to yourself and leave simplicity to the users. In addition to helping users eliminate tedious build operations, ConfigurationProperties also helps users reduce unnecessary configuration operations under the concept of "convention over configuration". And because of the existence of the application.properties file, even if customized configuration is required, all configurations only need to be performed in one file, which is very convenient to use. The adopted starters are all listed above.

Create Spring Boot Starter steps

Create starter project

Create ConfigurationProperties to save configuration information

Create AutoConfiguration and reference the defined configuration information

Implement all the operations that the starter should complete in AutoConfiguration, and add this class to the spring.factories configuration file for declaration

The package item introduces the project dependency into the SpringBoot project, and then you can use the starter

Specific steps:

Create a new starter project in idea, and directly execute the next step to generate the project.

SpringCloud-Spring Boot Starter usage test instance analysis

Add the following configuration file to the xml:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<?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>

    <artifactId>http-starter</artifactId>

    <version>0.0.1-SNAPSHOT</version>

  

    <!-- 自定义starter都应该继承自该依赖 -->

    <!-- 如果自定义starter本身需要继承其它的依赖,可以参考 https://stackoverflow.com/a/21318359 解决 -->

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starters</artifactId>

        <version>1.5.2.RELEASE</version>

    </parent>

  

    <dependencies>

        <!-- 自定义starter依赖此jar包 -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter</artifactId>

        </dependency>

        <!-- lombok用于自动生成get、set方法 -->

        <dependency>

            <groupId>org.projectlombok</groupId>

            <artifactId>lombok</artifactId>

            <version>1.16.10</version>

        </dependency>

    </dependencies>

  

</project>

Copy after login

Create the properties class to save the configuration information

1

2

3

4

5

6

7

8

@ConfigurationProperties(prefix = "http")

@Getter

public class HttpProperties {

  

    // 如果配置文件中配置了http.url属性,则该默认属性会被覆盖

    private String url = "https://blog.csdn.net/weixin_39709134?type=blog";

  

}

Copy after login

Create the business class:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

@Setter

@Getter

public class HttpClient {

  

    private String url;

  

    // 根据url获取网页数据

    public String getHtml() {

        try {

            URL url = new URL(this.url);

            URLConnection urlConnection = url.openConnection();

            BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));

            String line = null;

            StringBuilder sb = new StringBuilder();

            while ((line = br.readLine()) != null) {

                sb.append(line).append("\n");

            }

            return sb.toString();

        } catch (Exception e) {

            e.printStackTrace();

        }

        return "error";

    }

  

}

Copy after login

This business class contains the url attribute and a getHtml method, used to obtain a web page HTML data

Create AutoConfiguration

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@Configuration

@EnableConfigurationProperties(HttpProperties.class)

public class HttpAutoConfiguration {

  

    @Resource

    private HttpProperties properties; // 使用配置

  

    // 在Spring上下文中创建一个对象

    @Bean

    @ConditionalOnMissingBean

    public HttpClient init() {

        HttpClient client = new HttpClient();

  

        String url = properties.getUrl();

        client.setUrl(url);

        return client;

    }

  

}

Copy after login

In the above AutoConfiguration, we implemented our requirements: we created a bean of the HttpClient class in the Spring context, and we assigned a parameter in the properties to the bean.

Finally, we create a new directory META-INF under the resources folder, create a new spring.factories file in the directory, and # Configuring AutoConfiguration in ##spring.factories:

1

2

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\

com.nosuchfield.httpstarter.HttpAutoConfiguration

Copy after login

最后使用 Maven 打包该项目。之后创建一个 SpringBoot 项目,在项目中添加我们之前打包的 starter 作为依赖,然后使用 SringBoot 来运行我们的 starter

测试如下:

1

2

3

4

5

6

7

8

9

10

11

@Component

public class RunIt {

  

    @Resource

    private HttpClient httpClient;

  

    public void hello() {

        System.out.println(httpClient.getHtml());

    }

  

}

Copy after login

SpringCloud-Spring Boot Starter usage test instance analysis

之后可以在 application.properties中修改配置来进行测试证明 properties 中的数据确实被覆盖

The above is the detailed content of SpringCloud-Spring Boot Starter usage test instance analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

SpringBoot+Dubbo+Nacos development practical tutorial SpringBoot+Dubbo+Nacos development practical tutorial Aug 15, 2023 pm 04:49 PM

This article will write a detailed example to talk about the actual development of dubbo+nacos+Spring Boot. This article will not cover too much theoretical knowledge, but will write the simplest example to illustrate how dubbo can be integrated with nacos to quickly build a development environment.

See all articles