Spring Boot Framework Introduction

Now developed into a full Android stack development, put together the following information on the Spring Boot:

Boot advantage of a Spring framework

① good genes

Because SpringBoot is accompanied by Spring 4.0 born, boot the boot is the meaning, that is, in fact, its role is to help developers quickly build Spring framework, Spring SpringBoot inherited good genes, to develop more convenient in Spring fast.

② simplify coding

, Such as we want to create a web project using Spring's friends all know that when using Spring, you need to add more dependent on the pom file, and Spring Boot will help develop a rapid start a web container, in the Spring Boot we just need to add as a starter-web dependent to the pom file.

③ simplified configuration

Although the Spring framework for Java EE lightweight, but because of its cumbersome configuration, once was considered a "configuration hell." A variety of XML, Annotation configuration will be dazzling, and configure multiple, and if a mistake is difficult to find out why. Spring Boot more is the use of Java Config way for Spring configuration.

④ simplify deployment

When using Spring, when we need to deploy tomcat project deployment on the server, then the item labeled as war package thrown into the tomcat, after using Spring Boot, we do not need to go up the deployment in tomcat server because Spring Boot embedded tomcat we only need to project labeled jar package, using java -jar xxx.jar a button to start the project.

Further, to reduce the basic requirements of the operating environment, the environment variable in the JDK can.

⑤ simplify monitoring

We can introduce spring-boot-start-actuator depend directly using REST way to get the runtime performance parameters of the process, so as to achieve the purpose of monitoring, more convenient. But Spring Boot is just a micro framework does not provide a service discovery and registration of supporting functions, there is no integrated peripheral monitoring program, there is no perimeter security management solutions, so the micro-service architecture, used in conjunction Cloud Spring also need to match.

The main flow of execution of two Spring Boot

First, a new object is SpringApplication
performed during the method of the object SpingApplication

   1. 新建一个SpringApplication对象

Get webApplicationType type, when springboot war package as a packaging application, this type of SERVLET
injection ApplicationContextInitializer initializer
disposed listener ApplicationListener

   2. 执行对象的run方法,

Create a new StopWatch, and start to monitor the program run time
to obtain SpringApplicationRunListeners objects, and start the listener
passed in accordance with startup parameters args, Object New ApplicationArguments
New ConfigurableEnvironment object specific type StandardServletEnvironment, will load in its creation process springboot profile application.properties, while SpringApplication program in its bound
to create ConfigurableApplicationContext the object context, and the object set environment properties, traversing ApplicationContextInitializer the object is initialized,
obtain BeanFactory registered applicationArguments single through the context object
refresh execution context of operating

Principle of the three Spring Boot autoconfiguration

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {SpringApplication.run(MyApplication .class, args);}
}

We see, MyApplication class as the entrance, the entrance class has a main method, which is actually a standard entry method for Java applications, typically used in the main method SpringApplication.run () to start the entire application. It is worth noting that the entrance class to use @SpringBootApplication annotation declares that it is the core of SpringBoot comment.

@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 {
    // 略
}

This annotation inside, the most important is @EnableAutoConfiguration, so straightforward name, to see that it is to open the automatic configuration, SpringBoot begin to show up, so silently into @EnableAutoConfiguration source.

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

It can be seen in the notes to @EnableAutoConfiguration @import annotation configuration import completion, and is used inside EnableAutoConfigurationImportSelector SpringFactoriesLoader.loadFactoryNames method jar package scans with META-INF / spring.factories file. Here is 1.5.8.RELEASE achieving source:

 @Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    }
    try {
          AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
                    .loadMetadata(this.beanClassLoader);
          AnnotationAttributes attributes = getAttributes(annotationMetadata);
          //扫描具有META-INF/spring.factories文件的jar包
          List<String> configurations = getCandidateConfigurations(annotationMetadata,
                    attributes);
          //去重
          configurations = removeDuplicates(configurations);
          //排序
          configurations = sort(configurations, autoConfigurationMetadata);
           //删除需要排除的类
         Set<String> exclusions = getExclusions(annotationMetadata, attributes);
         checkExcludedClasses(configurations, exclusions);
         configurations.removeAll(exclusions);
         configurations = filter(configurations, autoConfigurationMetadata);
         fireAutoConfigurationImportEvents(configurations, exclusions);
         return configurations.toArray(new String[configurations.size()]);
    }
    catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
//加载spring.factories实现
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
        AnnotationAttributes attributes) {
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
            getSpringFactoriesLoaderFactoryClass(), 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;
}

Springboot any application that introduce springboot-autoconfigure, and spring.factories file in the package below. spring.factories document is in the form Key = Value, Value when a plurality of spaced, defined in this file information on initialization, monitor or the like, so that the real key is in effect automatically configured org.springframework.boot.autoconfigure.EnableAutoConfiguration ,As follows:

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
//省略

There are many automated configuration code we previously did not use the comments configuration:
@Configuration: This configuration would not do more to explain, we have been using
@EnableConfigurationProperties: This is an open comment using the configuration parameters, value is the value of our configuration entity ClassType parameter mapping, configuration entity as a configuration source.
The following condition is built SpringBoot annotation:
@ConditionalOnBean: SpringIoc container when the specified condition exists in the Bean
@ConditionalOnClass: SpringIoc container when the specified condition exists in the Class
@ConditionalOnExpression: SpEL expression as determined based on the condition
@ConditionalOnJava: a determination condition based on the version of the JVM
@ConditionalOnJndi: Find the location specified in the JNDI presence
@ConditionalOnMissingBean: when there is no designated Bean container in SpringIoc conditions
@ConditionalOnMissingClass: when there is no designated Class in SpringIoc container conditions
@ConditionalOnNotWebApplication: current condition item is not a Web project
@ConditionalOnProperty: Specifies whether the attributes are specified value
@ConditionalOnResource: whether the value specified classpath
@ConditionalOnSingleCandidate: When specifying only one in SpringIoc Bean container, or more, but although there are designated preferred Bean
@ConditionalOnWebApplication: The current project is a Web project conditions
above notes are meta-annotation @Conditional evolved, not in accordance with the conditions specific conditions created above the corresponding notes.

Published 10 original articles · won praise 8 · views 899

Guess you like

Origin blog.csdn.net/qq_44739668/article/details/104826807