Spring Boot features and modules

features

Spring Boot is the starting point for building Spring-based applications. Spring Boot is designed to get you up and running as fast as possible with minimal pre-configured Spring configuration.

The core features of Spring Boot are as follows:

  • Create a one-click Spring application.
  • Ability to use embedded Tomcat, Jetty, or Undertow without the need to deploy a WAR.
  • Provide customized starter Starters to simplify third-party dependency configuration.
  • Go for extreme automatic configuration of Spring.
  • Provide production environment features, such as metrics, health checks, and external configurations.
  • Zero code generation and zero XML configuration

There are also two very important policies in the Spring Boot framework: out of the box and convention over configuration.

  • Outof the box, Outofbox is a way to manage the life cycle of an object during development by adding dependency packages to the MAVEN project’s POM files and then using corresponding annotations instead of cumbersome XML configuration files. This feature frees developers from complex configuration and dependent administration to focus more on business logic.
  • Convention over Configuration is a software design paradigm in which SpringBoot itself configures the target structure and the developer adds information to the structure. This feature reduces some of the flexibility and increases the complexity of BUG locating, but it reduces the number of decisions developers have to make, eliminates a lot of XML configuration, and automates code compilation, testing, and packaging.

The core module

Spring Boot is built on the basis of the Spring Framework. Its main core is:

  • The Starter component provides components out of the box.
  • Auto-assembly, which automatically assembles beans based on context.
  • Actuator: Monitors Spring Boot applications.
  • Spring Boot CLI: Quickly build Spring Boot applications based on command line tools.

  • Spring-boot: Spring Boot core project.
  • Starters: Spring Boot startup service project. The list of built-in starters in Spring-Boot can be found in SpringBoot project source code project Spring-boot/Spring-Boot-Starters.
  • Autoconfigure: Spring Boot implementation of automatic configuration of the core project.
  • Actuator: Provides external supporting functions of Spring Boot applications. For example: application status monitoring management, application health indicator, remote shell support.
  • Tools: Provides a common tool set for Spring Boot developers.
  • Cli: Spring Boot command line interactive tool, which can be used for rapid prototyping using Spring. You can use it to run Groovy scripts directly. If you don’t like Maven or Gradle, use the CLI (Command Line Interface) to develop and run Spring applications. You can use it to run Groovy scripts and even write custom commands.

Principle of Spring Boot automatic assembly

Realization of automatic assembly

Automatic assembly in SpringBoot is enabled via the @enableAutoConfiguration annotation, which is declared in the bootstrap class annotation @SpringBootApplication.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {}
Copy the code

In the @enableAutoConfiguration annotation, you can see that in addition to the @import annotation, There is also an @AutoConfigurationPackage annotation that scans all components in the package and subpackages of the class that uses the annotation into the SpringIoC container. And @ Import annotations Import is not a Configuration in the Configuration of the class, but a AutoConfigurationImportSelector class.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {}
Copy the code

AutoConfigurationImportSelector ImportSelector is achieved, it is only one selectImports abstract methods, and returns a String array, the array can be specified to assembly to the IoC container classes, When an ImportSelector implementation Class is imported in @import, the Class names returned from that implementation Class are loaded into the IoC container. Unlike @Configuration, ImportSelector can be assembled in batches, and optionally assembled beans can be logically handled to determine which classes can be initialized by the IoC container based on the context.

public interface ImportSelector { String[] selectImports(AnnotationMetadata var1); @Nullable default Predicate<String> getExclusionFilter() { return null; }}Copy the code

example

// Start by creating two classes that we need to assemble into the IoC container. Public class FirstClass {} public class SecondClass {} public class SecondClass {} public class SecondClass {} // This means that the two beans will be assembled into the IoC container. public class GpImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { return new String[]{FirstClass.class.getName(),SecondClass.class.getName()}; }} // Create a startup class, annotate it with @import and @AutoConfigurationPackage, and get the FirstClass object instance from the IoC container via ca.getBean. @SpringBootApplication @AutoConfigurationPackage @Import({GpImportSelector.class}) public class DemoApplication { public  static void main(String[] args) throws IOException { ConfigurableApplicationContext ca =SpringApplication.run(DemoApplication.class, args); FirstClass bean = ca.getBean(FirstClass.class); }Copy the code

The advantage of this implementation over @import (* configuration.class) lies in the flexibility of assembly and batch implementation.

Automatic assembly principle analysis

In an AutoConfigurationImportSelector to locate selectlmports method, which is ImportSelector interface implementation, this method has two main functions:

  • AutoConfigurationMetadata. LoadMetadata method from the meta-inf/spring – autoconfigure – metadata. The properties of load automatic assembly condition of metadata, Simply put, only beans that meet the conditions can be assembled.
  • Collect all the eligible configuration class autoConfigurationEntry. GetConfigurations (), complete the automatic assembly.

Selectlmports () and loadMetadata() methods

public String[] selectImports(AnnotationMetadata annotationMetadata) { if (! this.isEnabled(annotationMetadata)) { return NO_IMPORTS; } else { AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader); AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata); return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations()); }} / / meta-inf/spring - autoconfigure - metadata. The properties of the static loading AutoConfigurationMetadata loadMetadata (this classLoader) { return loadMetadata(classLoader, "META-INF/spring-autoconfigure-metadata.properties"); }Copy the code

Collect all the eligible configuration class autoConfigurationEntry. GetConfigurations () method

protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) { if (! this.isEnabled(annotationMetadata)) { return EMPTY_ENTRY; } else {// Get the attributes of @enableAutoConfiguration exclude, excludeName, etc. AnnotationAttributes attributes = this.getAttributes(annotationMetadata); / / get all automatic assembly configuration class List < String > configurations = this. GetCandidateConfigurations (annotationMetadata, attributes); // Delete the duplicate configuration item configurations = this.removeDuplicates(configurations); // Exclude as configured in the @enableAutoConfiguration annotation Set<String> exclusions = this.getexclusions (annotationMetadata, attributes); this.checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = this.filter(configurations, autoConfigurationMetadata); / / this broadcast events. FireAutoConfigurationImportEvents (configurations, exclusions); / / return after multilayer judgment and filtering the configuration class set return new AutoConfigurationImportSelector. AutoConfigurationEntry (configurations, exclusions); }Copy the code

In general, it obtains all configuration classes first, and obtains the configuration classes that need to realize automatic assembly through operations such as de-duplication and exclude. GetCandidateConfigurations, it is the most core method to obtain the configuration class.

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
    Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
    return configurations;
}
Copy the code

The SpringFactoriesLoader, which is a conventional loading method provided by Spring, is similar to the SPI in Java. It scans the meta-INF /spring.factories file in the classpath where the data is stored as Key=Value. SpringFactoriesLoader loadFactoryNames obtains the corresponding value based on the Key. Therefore, this scenario, the Key corresponding to EnableAutoConfiguration, the Value is more configuration class, also is the Value returned by getCandidateConfigurations method.

# AutoConfigureCache auto-configuration imports
org.springframework.boot.test.autoconfigure.core.AutoConfigureCache=\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration

# AutoConfigureDataJpa auto-configuration imports
org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureDataJpa=\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
.......
Copy the code

In addition to the basic @Configuration annotation, each XXXAutoConfiguration has a @conditionalonclass annotation, which is used for this purpose. Determine if RabbitTemplate and Channel classes exist in the CLASspath, and if so, register the current configuration class with the IoC container. In addition, @ EnableConfigurationProperties is the configuration properties, that is to say, we can in accordance with the contract in applicationproperties configuration parameters of the RabbitMQ, the configuration will be loaded into the RabbitProperties. In fact, all of these things are inherent in Spring.

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({RabbitTemplate.class, Channel.class})
@EnableConfigurationProperties({RabbitProperties.class})
@Import({RabbitAnnotationDrivenConfiguration.class})
public class RabbitAutoConfiguration {
Copy the code

summary

At this point, the principle of automatic assembly is basically analyzed, and the core process is summarized simply:

  • Through @ Import (AutoConfigurationImportSelector) to realize the configuration class Import, but it is not in the traditional sense of the single configuration class assembly.
  • AutoConfigurationImportSelector class implements the ImportSelector interface, rewrite the method selectImports, which is used to realize the selective assembly in batch configuration class.
  • Using the SpringFactoriesLoader mechanism, you can scan meta-INF/SpringFactories in the CLASspath path to read configuration classes for automatic assembly.
  • The configuration classes that do not meet the conditions are removed by filtering conditions to complete automatic assembly.

Automatic configuration

Spring Boot also provides the spring-autoconfigure-metadata.properties file to implement batch automatic assembly condition configuration. It does the same thing as @Conditional, except that these Conditional configurations are placed in the configuration file. The following configuration comes from the/meta-INF /spring-autoconfigure-metadata.properties file in the spring-boot-autoconfigure JAR package.

org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration= org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration.AutoConfigureAfter=org.springframework.b oot.autoconfigure.http.HttpMessageConvertersAutoConfiguration org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration.ConditionalOnClass=com.data stax.driver.core.Cluster,reactor.core.publisher.Flux,org.springframework.data.cassandra.core.ReactiveCassandraTemplate org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration.ConditionalOnClass=org.apache.solr.cl ient.solrj.SolrClient,org.springframework.data.solr.repository.SolrRepository org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration.ConditionalOnWebAppl ication=SERVLET org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration=Copy the code

This form is also the embodiment of “convention over configuration”. Two conditions must be followed to realize condition filtering in this configuration mode:

  • The configuration file path and name must be/meta-INF /spring-autoconfigure-metadata.properties.
  • The configuration format of the key in the configuration file is as follows: Class full path name condition = value of the automatic configuration class.

The benefit of this configuration approach is that it effectively reduces Spring Boot startup time. This filtering reduces the number of configuration classes that are loaded, because this filtering occurs before the configuration classes are loaded, so it reduces the time it takes to load beans when Spring Boot is started.

In-depth physical

Spring Boot Actuator. It provides many production-level features, such as monitoring and measuring Spring Boot applications. These features are available through many REST endpoints, remote shells, and JMX.

The key feature of Spring Boot Actuator is that it provides many Web endpoints inside apps to learn what’s going on inside apps while they’re running. With the Actuator, you can learn how the beans are assembled in the Spring application context, learn the environment properties that the application can access, and get snapshots of runtime metrics…

Physical endpoint

To enable the endpoints of the Actuator, simply introduce the starter dependencies of the Actuator into the project. The Actuator provides 13 endpoints

  • GET/AutoConfig provides an auto-configuration report that records which auto-configuration criteria passed and which did not
  • GET /configprops describes how configuration properties (including default values) inject beans
  • GET/Beans describes all beans in an application context and their relationships
  • GET /dump takes a snapshot of thread activity
  • GET /env Gets all environment attributes
  • GET /env/{name} gets the value of a specific environment attribute by name
  • GET/Health reports on the application’s health metrics, which are provided by the HealthIndicator implementation class
  • GET /info Gets the customization information for the application, provided by the info header property
  • GET/Mappings Describes all URI paths and their mappings to controllers (including endpoints)
  • GET /metrics reports various application metrics, such as memory usage and HTTP request counts. GET /metrics/{name} reports application metrics of a given name
  • POST/shutdown close the application to endpoints. The shutdown, enabled is set to true
  • GET/Trace provides basic HTTP request tracing information (timestamp, HTTP, etc.)

Protecting Actuator endpoints

Many of the endpoints publish information that may involve sensitive data, and some endpoints, such as /shutdown, are dangerous and can be used to shutdown applications. Therefore, it is important to secure these endpoints so that only authorized clients can access them. In fact, the endpoints of the Actuator can be protected in the same way as other URL paths – using Spring Security. In Spring Boot applications, this means adding Security starter dependencies as build dependencies, and then having security-related automatic configurations to protect the application, including of course the endpoints.

Spring Boot developer tools

Spring Boot introduces a new set of developer tools that make it easier for you to use Spring Boot while developing, including the following features.

Automatic restart: Automatically restarts running applications when files in the Classpath change.

LiveReload support: Changes to a resource automatically trigger a browser refresh.

Remote development: Automatic restart and LiveReload support for remote deployment.

Default development-time property values: Provide meaningful default development-time property values for some properties.

Spring Boot’s developer tools take the form of libraries that can be added to projects as dependencies. Add in Maven POM

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
</dependency>
Copy the code

The developer tools are disabled when the application is running as a fully packaged JAR or WAR file, so there is no need to remove this dependency before building the production deployment package.

Automatic restart

Any changes to the file in the Classpath trigger a restart of the application. To make the restart fast, unmodified classes (such as those in third-party JAR files) are loaded into the base class loader, while the application code is loaded into a separate restart class loader. When changes are detected, only the restart classloader restarts. Some resource changes in the Classpath do not require a restart of the application. View templates like Thymeleaf can be edited directly without restarting the application. Static resources in /static or /public also do not need to restart the application, so Spring Boot developer tools will exclude the following directories on reboot: / meta-inf /resources, /resources, /static, /public, and /templates. . You can set the spring devtools. Restart. Exclude property to override the default restart out directory.

Can completely shut down automatically restart, spring. Devtools. Restart. Enabled is set to false

LiveReload

Spring Boot’s developer tools integrate with LiveReload (livereload.com) to eliminate the refresh step. Spring Boot starts an embedded LiveReload server that triggers a browser refresh when a resource file changes. All you have to do is install the LiveReload plugin in your browser. Disable the built-in LiveReload servers, can be spring. The devtools. LiveReload. Enabled is set to false.

Remote development

Set a remote security code to enable remote development:

spring:devtools:remote:secret:myappsecret 
Copy the code

With this property, the running application starts a server component to support remote development. It listens for requests to accept changes and can restart the application or trigger a browser refresh. To use the remote server, you need to run the remote development tool client locally. This is a class a remote client, the fully qualified class name is org. Springframework. Boot. Devtools. RemoteSpringApplication. It runs inside the IDE and asks for a parameter to tell the remote application where to deploy.

reference

Spring Cloud Alibaba micro service principle and practice