How can I use springboot everyday without knowing its principle of automatic assembly?

root429 2021-01-22 10:58:44
use springboot everyday knowing principle


A reader is interviewing recently , Such a question was asked in the interview “ Look, you've used springboot, Tell me springboot How is the automatic configuration of ?” This should be a springboot One of the most common interview questions . Let's take this question and dissect it together springBoot The principle of automatic configuration .

SpringMvc and SpringBoot contrast

First of all, let's go back to building a springmvc Of hello-word Of web project (xml Configured ) Are we going to be in pom Import various dependencies in , Then there may be version conflicts among the dependencies, which need to be excluded . When you go through a lot of hardships to solve the dependence , And then you need to write web.xml、springmvc.xml Configuration files, etc . We just want to write individual hello-word It's just a project , It's really a lot of time spent on configuration files and jar Package dependency . Greatly affected the efficiency of our development , And increased web Difficulty of development . To simplify this complex configuration 、 And the conflicting dependencies of each version ,springBoot It came into being . We now pass idea Create a springboot The project was solved in minutes , You don't need to care about the configuration ( Zero configuration is basically realized ). Let you really realize out of the box .SpringBoot It saves you a lot of time to spend with your girlfriend , No, programmers don't have girlfriends ?( If not, you can new One of them ) It not only allows you to spend more time on your business logic development , And it's greatly reduced web The threshold of development . therefore SpringBoot It's better to understand people's clothes , Wrong, wrong, understanding , Know where the pain points of developers are .
 Insert picture description here

SpringBoot Automatic configuration loading

since Springboot Even though it's so easy to use , But as a user , We're still curious about how it helps us out of the box .Spring Boot There is a global profile or application.yml. In this global file, you can configure various parameters, such as you want to change the port server.port Or you want to adjust the level of the log, all can be configured . For more properties that can be configured, please refer to the official website .

So many attributes , How do these properties work in a project ?SpringBoot There is no configuration for the project , To configure ”( or application.yml With the exception of ), Both However, there is no breakthrough in configuration , Then we can only find the entry from the startup class . The startup class is a bare one main Method , There is only one note on the class SpringBootApplication
The note is Spring Boot Essential notes for the project . So the principle of automatic configuration must have something to do with this annotation ! Let's take a look at this annotation .
@SpringBootApplication annotation

@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

There's nothing to say about the top four notes , If you have basically implemented a custom annotation , We all know what difference means .

  • @SpringBootConfiguration Inherited from @Configuration, The two functions are the same , Note that the current class is a configuration class .
  • @ComponentScan It is mainly used to specify scan path on class or interface , Follow Xml Inside <context:component-scan base-package="" /> The configuration is the same .springboot If you don't write this scan path , The default is the path to start the class .
  • @EnableAutoConfiguration
public @interface EnableAutoConfiguration {

Let's focus on this note AutoConfigurationImportSelector This class getCandidateConfigurations
In this method SpringFactoriesLoader.loadFactoryNames() Scan all with META-INF/spring.factories Of jar package ( spring.factories We can understand that Spring Boot Their own SPI Mechanism ).
spring-boot-autoconfigure-x.x.x.x.jar There's one in there spring.factories file .spring.factories Files are made up of groups of Key = value In the form of , One of them key yes EnableAutoConfiguration The full class name of the class , And its value It's an example. AutoConfiguration List of class names at the end of , Yes redis、mq Wait for the class names to be separated by commas .
 Insert picture description here

 Insert picture description here
We're going back to getAutoConfigurationEntry This method will be executed when getCandidateConfigurations In this method, we can see that a total of 127 Autoconfig classes .
 Insert picture description here
Do these classes have to be loaded in ?springboot Still not so stupid , It advocates loading on demand .

  • It removes duplicate classes
  • Filter it out. We configured it exclude The configuration below the annotated class will be filtered out RestTemplateAutoConfiguration This class
     Insert picture description here
  • After the above treatment , The rest of the auto configuration classes, if they're going to work , It is necessary to meet certain conditions . If these conditions are satisfied spring boot It's done through conditional annotations .

@ConditionalOnBean: When there is a designation in the container Bean Under the condition of
@ConditionalOnClass: When there is a specified class in the classpath
@ConditionalOnExpression: be based on SpEL Expression for true It is only instantiated as a judgment condition
@ConditionalOnJava: be based on JVM Version as a condition of judgment
@ConditionalOnJndi: stay JNDI Find the specified location if it exists
@ConditionalOnMissingBean: When there is no designation in the container Bean Under the circumstances
@ConditionalOnMissingClass: When there is no specified class in the container
@ConditionalOnWebApplication: The current project Web Under project conditions
@ConditionalOnNotWebApplication: The current project is not Web Under project conditions
@ConditionalOnProperty: Whether the specified property has the specified value
@ConditionalOnResource: Whether the class path has the specified value
@ConditionalOnOnSingleCandidate: When specifying Bean There's only one in the container , Or more than one but specify the preferred one Bean

These notes are all combined @Conditional annotation , It's just that different combinations of conditions are used, and finally true To instantiate the class that needs to be instantiated , Otherwise, ignore filtering out . When we go back to the code, we can see that after the conditional judgment and filtering, we have left the auto configuration classes that meet the conditions, only 23 A the . The others are filtered because they don't satisfy the condition annotation .
 Insert picture description here
If we want to know which autoconfiguration classes are filtered , What's the reason it's filtered , And which classes are loaded .spring boot It's all in the journal for us . It's still very sweet . We can adjust the level of our log to debug. Then we can see the following log
Positive matches: Insert picture description here
Here we intercept part of the log . There are four parts in total :

  • Positive matches@Conditional Condition is true , Configuration class is Spring Container loading .
  • Negative matches: @Conditional The condition is false , Configuration class is not Spring Container loading .
  • Exclusions: We've identified classes that don't need to be loaded . For example, start the class configuration above RestTemplateAutoConfiguration class
  • Unconditional classes: Autoconfig classes do not contain any class level conditions , in other words , Classes are always loaded automatically .

Automatic configuration takes effect

We use ServletWebServerFactoryAutoConfiguration For example, configure a class , Explain how the properties in the global configuration file work , such as :server.port=88, How it works ( Of course, if it is not configured, there will be default values , This default value comes from org.apache.catalina.startup.Tomcat).

// Marked as configuration class
@Configuration(proxyBeanMethods = false)
// If there is ServletRequest.class Will take effect
@ConditionalOnWebApplication(type = Type.SERVLET)
// hold @ConfigurationProperties The annotated class injection is Spring Container of Bean.
@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,
ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })
public class ServletWebServerFactoryAutoConfiguration {

We can find out EnableConfigurationProperties It's configured in the annotation ServerProperties.class

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties {
* Server HTTP port.
private Integer port;

There is an annotation on this class :@ConfigurationProperties, Its function is to bind properties from the configuration file to the corresponding bean On ( That is to put us Corresponding server.port Mapping to ServerProperties Class port attribute ) and @EnableConfigurationProperties This annotation is to bind the attribute of beanServerProperties) Injection into spring In the container ( amount to @Component The annotation is the same ).
All the properties that can be configured in the configuration file are in xxxxPropertites Class encapsulates , The configuration file can refer to the property class corresponding to a function .
By now, I should be able to answer the question at the beginning of the article , Interview should not need to answer so detailed, you can refer to the following answers :

Spring Boot When it starts, it will go through @EnableAutoConfiguration Notes found META-INF/spring.factories All autoconfiguration classes in the configuration file , And load it , And these auto configuration classes are based on AutoConfiguration It's named at the end , It's actually a JavaConfig Formal Spring Container configuration class , It can be achieved by Properties In the class named at the end, get the properties configured in the global configuration file, such as :server.port, and XxxxProperties Class is through @ConfigurationProperties The annotation is bound to the corresponding attribute in the global configuration file .

I found a picture on the Internet , Basically, the automatic assembly process has been explained clearly .
 picture source


  • SpringBoot Startup loads a large number of autoconfig classes ( adopt “SPI” The way ), Then it will reserve some required classes according to the conditional annotation .
  • We introduce a new component , You can have a look first springBoot Is there a default offer .
  • SpringBoot Basically achieved “ Zero configuration “, And out of the box .



  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云