Spring Boot of combat customize their starter

This article first appeared personal website, the original address: http: //www.javaadu.online/ p = 535, For reprint, please indicate the source?

Spring Boot in the process of learning, the most contact is starter. Starter can be considered a service - allows developers to use a feature does not need to deal with various dependencies of attention, does not require specific configuration information from Spring Boot automatically by Bean class found in the classpath needs, and woven into the bean. For example, the Spring-jdbc-the Boot-starter existence of this starter, so we only need to use in BookPubApplication @Autowiredthe DataSource bean can be introduced, Spring Boot automatically creates an instance of the DataSource.

Here we will use a rather unusual starter shows the operating principle of the automatic configuration of Spring Boot. Spring Boot automatic configuration, Command-line Runner in an article has used StartupRunner first class database query the number of books after the program starts running, and now another demand: the number of prints of each entity after the system starts .

How Do

  • Create a new module db-count-starter , and then modify the file pom db-count-starter module increases corresponding library.
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot</artifactId>
        <!-- version继承父模块的-->
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
        <version>1.9.3.RELEASE</version>
    </dependency></dependencies>
  • New packet structure COM / Test / bookpubstarter / dbcount , then a new class DbCountRunner achieve CommandLineRunner interface, the output number of each entity in the run method.
package com.test.bookpubstarter.dbcount;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.repository.CrudRepository;
import java.util.Collection;

public class DbCountRunner implements CommandLineRunner {
    protected final Logger logger = LoggerFactory.getLogger(DbCountRunner.class);
    private Collection<CrudRepository> repositories;

    public DbCountRunner(Collection<CrudRepository> repositories) {
        this.repositories = repositories;
    }
    @Override
    public void run(String... strings) throws Exception {
        repositories.forEach(crudRepository -> {
            logger.info(String.format("%s has %s entries",
                    getRepositoryName(crudRepository.getClass()),
                    crudRepository.count()));
        });
    }

    private static String getRepositoryName(Class crudRepositoryClass) {
        for (Class repositoryInterface : crudRepositoryClass.getInterfaces()) {
            if (repositoryInterface.getName().startsWith("com.test.bookpub.repository")) {
                return repositoryInterface.getSimpleName();
            }
        }
        return "UnknownRepository";
    }
}
  • Increase the automatic configuration file DbCountAutoConfiguration
package com.test.bookpubstarter.dbcount;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.repository.CrudRepository;
import java.util.Collection;

@Configuration
public class DbCountAutoConfiguration {
    @Bean
    public DbCountRunner dbCountRunner(Collection<CrudRepository> repositories) {
        return new DbCountRunner(repositories);
    }
}
  • New in src / main / resources directory META-INF folder, and then create spring.factories file that tells Spring Boot find the specified automatic configuration file, so its content is
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.test.bookpubstarter.dbcount.DbCountAutoConfiguration
  • In the program on the basis of previous, increased reliance starter at the top level pom file
<dependency>
   <groupId>com.test</groupId>
   <artifactId>db-count-starter</artifactId>
   <version>0.0.1-SNAPSHOT</version>
</dependency>
  • The StartupRunner related comment out, then right at the main function of the Run BookPubApplication.main (...) , we can see that the main program is written starter used.

A simple demonstration of their starter .png

analysis

Regular starter is an independent project, and then publish the new warehouse in maven registered in that other developers can use up your starter.

Common starter will include several aspects of the following:

  1. Automatic configuration file, according to the presence or absence of a specified class classpath to decide whether to perform the auto-configuration feature.
  2. spring.factories, very important, guiding Spring Boot find the specified automatic configuration file.
  3. endpoint: can be understood as a admin, it contains a description of the service, interface, interactivity (query business information)
  4. Indicators of health services provided by the starter: health indicator

In the application startup, Spring Boot using SpringFactoriesLoader class loader looks org.springframework.boot.autoconfigure.EnableAutoConfiguration keywords corresponding Java profile. Spring Boot traverses in each jar Pouchong META-INF directory spring.factories files, to construct a profile list. In addition to EnableAutoConfiguration keywords corresponding configuration file, there are other types of configuration files:

  • org.springframework.context.ApplicationContextInitializer
  • org.springframework.context.ApplicationListener
  • org.springframework.boot.SpringApplicationRunListener
  • org.springframework.boot.env.PropertySourceLoader
  • org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider
  • org.springframework.test.contex.TestExecutionListener

Spring Boot the starter does not depend on Spring Boot libraries at compile time. This example relies spring boot is not automatically configured to use since spring boot, but simply because the need to achieve CommandLineRunner interface.

Two points to note

  1. @ConditionalOnMissingBean role: only the corresponding ban have not been created in the system, it modifies the initialization code block will be executed, the user's own manually created bean priority ;

  2. How to find Spring Boot starter automatic configuration file (file xxxxAutoConfiguration and the like)?

  • spring.factories: a trigger Spring Boot class classpath directory under detection, automatic configuration;
  • @Enable : sometimes need a starter's trigger user * Find Automatic configuration files.

Spring Boot 1.x series

  1. Spring Boot automatic configuration, Command-line-Runner
  2. Understanding Automatic configuration of Spring Boot
  3. Spring Boot of @PropertySource notes in the integration of Redis
  4. Spring Boot project, how to customize HTTP message converter
  5. Spring Boot Restful interface to provide integrated Mongodb
  6. Spring bean in scope
  7. Spring Boot event dispatcher used in the project mode
  8. Error handling practices when Spring Boot provides RESTful interface

This focus on the number of back-end technology, JVM troubleshooting and optimization, Java interview questions, personal growth and self-management, and other topics, providing front-line developers work and growth experience for the reader, you can expect to gain something here.
Jwadu

Guess you like

Origin www.cnblogs.com/javaadu/p/11742881.html