You have been how it was used in the Spring Boot Starters

Spring Boot Spring MVC contrast biggest advantage is simple to use, is greater than the agreed configuration. Not like before when using Spring MVC, and from time to time been engaged in confusing xml configuration files, and snatched a little because of negligence on the xml configuration, resulting in the project somehow unavailable, he felt nothing attachment to life, referred to no love.

This is due to the composition of a variety of starters Spring Boot, there are official, there are third-party open source it. It can be said, basically you plan to use functionality can be found, if not found, then look for it.

Spring Boot with functional components (e.g., spring-boot-starter-actuator, spring-boot-starter-data-redis etc.) is very simple step using a method known to summarize the elephant fridge, then the following three steps you can be completed using the component's functionality:

STEP 1

Pom introduced in the corresponding packet file, for example:

<dependency>

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

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

</dependency>

STEP 2

Join in the application configuration file in the appropriate configuration, the configuration components are a good agreement, need to see official documents or instructions. Some of the more complex components, the corresponding parameters and rules correspondingly large, somewhat likely how the tens of hundreds.

STEP 3

Under the above two steps are normal, we can come to develop business functions related to the use of interface components provide.

Yes, right, we do not know the process has been practiced many times in the daily development. So Spring Boot Why is so simple to use it can do, it is what kind of internal working mechanism, it does not know if you have not studied.

The following is to understand the components implementation mechanism Spring Boot and made a demo starter. Understand the principles involved, what is the meaning of our future work?

1. When experiencing problems, they can help us more idea of ​​troubleshooting;

2. You can help us to correctly read the source code, the entry point of the assembly where, what, and so on configuration properties;

the above

The following, began to realize this simple starter, the starter and no real function, just to be a demonstration of it.

Before we begin, we need to understand what spring boot starter is it?

In fact starter function does not contain much code, we can understand it as a "connectivity package" (made my own concept), in accordance with this concept is: First, it is a package, a collection, it is the need of other features include components come in, put it in your pom file. Then it is a connection, it introduced the components of our project and make a connection, and eliminates the need for complex configurations to help us, trying to do the simplest in the middle.

There are four elements to achieve a starter:

starter named;

Automatic configuration class, the bean is used to initialize relevant;

Automatic configuration specified class profile spring.factories;

Custom attribute entity class declaration attribute starter application configuration;

Well, to start to achieve our demo

1. a name to the starter

That is when we use it artifactId referenced in the pom. There are naming rules, the official regulations:

The official names of the form of starter spring-boot-starter- {name}, for example, spring-boot-starter-actuator mentioned above.

starter unofficial naming format {name} -spring-boot-starter, since we have given starter named kite-spring-boot-starter, named in the pom file.

<groupId>kite.springcloud</groupId>

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

<packaging>jar</packaging>

<version>1.0-SNAPSHOT</version>

2. Automatic configuration package and the introduction of other dependent packages

Starter achieve automatic configuration depends annotation, to be introduced so that the automatic configuration of two packages in the pom jar

<dependency>

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

    <artifactId>spring-boot-configuration-processor</artifactId>

</dependency>

<dependency>

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

    <artifactId>spring-boot-autoconfigure</artifactId>

</dependency>

In addition, of course, also depend on other packages imported.

3. Create a file spring.factories

Create a name for the file in the spring.factories resource / META-INF directory, why here? When Spring Boot startup, will look at all the classpath named spring.factories file, and then run inside the specified configuration is automatically loaded class, the specified class (one or more) initialization of the relevant bean.

For example the configuration information in the present embodiment is such that:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\

  kite.springcloud.boot.starter.example.KiteAutoConfigure

Is fixed in front of the equal sign written, the back is automatically configured our custom class, if there is a plurality of words, separated by commas.

4. Preparation based autoconfiguration

Class is used to initiate automatic configuration of the relevant starter bean. It can be said to achieve the core functionality starter.

@Configuration

@ConditionalOnClass(KiteService.class)

@EnableConfigurationProperties(KiteProperties.class)

@ slf4j

public class KiteAutoConfigure {

    @Autowired

    private KiteProperties kiteProperties;

    @Bean

    @ConditionalOnMissingBean(KiteService.class)

    @ConditionalOnProperty(prefix = "kite.example",value = "enabled", havingValue = "true")

    KiteService kiteService(){

        return new KiteService(kiteProperties);

    }

}

The code is very simple, looking ahead, the most is the variety of comments.

@Configuration this need not explain, that this is automatic configuration class, will be used when we usually do the project, is generally used when reading configuration file.

@ConditionalOnClass(KiteService.class) :

In the case only to find KiteService class in the classpath, will resolve this automatic configuration class, or do not resolve.

@EnableConfigurationProperties(KiteProperties.class):

Enable configuration class.

@Bean: instantiate a bean.

@ConditionalOnMissingBean(KiteService.class):

@Bean used with the case where only a case of code blocks before performing the annotation of the bean does not exist in the current context, i.e. the current context of yet KiteService bean instance, will perform kiteService () method, examples of such example of a bean out.

@ConditionalOnProperty:

When an application in the configuration file related to the configuration it will execute a block of code annotations.

The meaning of this is that the whole class: parsing when there KiteService class classpath configuration in this category, under what circumstances will exist in the classpath, that is, the relevant project references jar package. And there is no instance of the bean in the context of KiteService case, a new new instance out, and the configuration application configuration incoming values.

5. Implement the class attribute configuration

@Data

@ConfigurationProperties("kite.example")

public class KiteProperties {

    private String host;

    private int port;

}

Configuration class is very simple, only two properties, a host, a port. Kite.example prefixed configuration parameters. Later, when we use the starter you will see how to declare configuration properties.

6. Implement class-related functions

That is KiteService has been mentioned earlier, in fact, strictly speaking, this kind of business functions should not be placed starter, the jar should be placed in a separate bag, but here is very simple demo, where it wrote.

@ slf4j

public class KiteService {

    private String host;

    private int port;

    public KiteService(KiteProperties kiteProperties){

        this.host = kiteProperties.getHost();

        this.port = kiteProperties.getPort();

    }

    public void print(){

        log.info(this.host + ":" +this.port);

    }

}

A constructor and a print method.

7. Packaging

By maven command will install the starter to the local maven repository

mvn install

You can also publish to your PW by mvn package deploy

Or posted to the central warehouse.

Above starter has completed the development and installation to the local repository, and then is to use it in our project.

1. Create a project, quoted in the pom

<dependency>

    <groupId>kite.springcloud</groupId>

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

    <version>1.0-SNAPSHOT</version>

</dependency>

2. Application configuration item

Creating application.yml, configuration is as follows:

server:

  port: 3801

kite:

  example:

    enabled: true # turn to take effect

    host: 127.0.0.1

    port: 3801

3. Call the service method KiteService

@RestController

@RequestMapping(value = "use")

public class UseController {

    @Autowired

    private KiteService kiteService;

    @GetMapping(value = "print")

    public void print(){

        kiteService.print();

    }

}

4. Start services, and access interface

Access / use / print interfaces, you will find print out the configuration information in the log

2019-05-24 16:45:04.234  INFO 36687 --- [nio-3801-exec-1] k.s.boot.starter.example.KiteService    : 127.0.0.1:3801

Follow the above ideas, we look at the official structure of the starters. First come the Spring Boot from the github clone copy down. With the idea to open, you can see that the project is structured as follows

13897885-52a59b43b8ab8a8b.png

The main starters Spring-boot-starters in that official, such as jdbc, redis, security, web, and so on.

We get spring-boot-starter-data-redis this starter as an example, the official is to talk about how the organization structure of the project, and the order to read the source code should be like.

1. Expand redis starter in Spring-boot-staters, we see the directory structure is as follows

13897885-bda045504f81c6d9.png

Java code which is not only a spring.provides file, which reads as follows:

provides: spring-data-redis,lettuce-core

That means, the item dependent on spring-data-redis and lettuce-core two packages, and references in the pom file. Its purpose is to inform the user when referring to this package, no longer provides a reference in the dependent package.

2. Next is the automatic annotation, all stater automatic annotation class, property configuration classes put under spring-boot-autoconfigure this project

13897885-7946007f5204130d.png

Spring.factories not see the familiar, realized in front of our own. The more content, we look at the relevant redis

org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\

org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\

org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration

Contains three auto-configuration file, and then follow the configuration, we find where the package

13897885-d420ac1b07acd933.png

Then you can start reading the code. Other starter is the same structure.

Welcome to work one to five years of Java engineer friends to join Java programmers: 721 575 865

Java architecture to provide free learning materials within the group (which has high availability, high concurrency, high performance and distributed, Jvm performance tuning, Spring Source, MyBatis, Netty, Redis, Kafka, Mysql, Zookeeper, Tomcat, Docker, Dubbo, more knowledge of information architecture Nginx, etc.) rational use of every minute of their own time to enhance their learning, do not use the "no time" to hide his ideological laziness! Young, hard fight, give an account of their own future!

Reproduced in: https: //www.jianshu.com/p/94bda3b0ef68

Guess you like

Origin blog.csdn.net/weixin_33753845/article/details/91205127