Spring引导如何创建自动配置class

Spring Boot how to create Auto configuration class

我是 Spring Boot 的初学者。当我在 Spring Boot 中使用任何依赖项时,它们具有默认的自动配置。

我的问题是:

  1. 什么是自动配置 class?
  2. 自动配置如何工作?
  3. 如何实现自己的自动配置?

请向我推荐任何描述简单方式的博客,或者请提供任何代码片段以便我更好地理解。

Spring 引导核心包 spring-boot-starter 包含 spring-boot-autoconfigure 包。

它有什么作用?(来自 JavaDoc)

Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined. For example, If you have tomcat-embedded.jar on your classpath you are likely to want a TomcatEmbeddedServletContainerFactory (unless you have defined your own EmbeddedServletContainerFactory bean).

Auto-configuration tries to be as intelligent as possible and will back-away as you define more of your own configuration. You can always manually exclude() any configuration that you never want to apply (use excludeName() if you don't have access to them). You can also exclude them via the spring.autoconfigure.exclude property. Auto-configuration is always applied after user-defined beans have been registered.

所以类路径中的每个 Spring 可以自动配置的 jar,Spring 将自动配置供您在应用程序中使用。想想 Hibernate、ThymeLeaf、Jackson 等

如何使用?

只需在您的应用程序中添加 @EnableAutoConfiguration 即可 Spring 自动配置您的应用程序(您可能还需要 @SpringBootConfiguration)。

@SpringBootConfiguration
@EnableAutoConfiguration
// Or just @SpringBootApplication instead of the 2 above
@Import(AppConfig.class)
public class App {
  public static void main(String[] args) {
    SpringApplication.run(App.class);
  }
}

一切顺利。

它能为您配置什么? 以下所有这些工具(通过查看 org.springframework.boot.autoconfigure 包获得)

admin
amqp
aop
batch
cache
cassandra
cloud
condition
context
couchbase
dao
data
analyzer
domain
jest
flyway
freemarker
template
gson
h2
hateoas
hazelcast
info
integration
jackson
jdbc
jersey
jms
jmx
jooq
kafka
ldap
liquibase
logging
mail
mobile
mongo
mustache
jpa
reactor
security
sendgrid
session
social
solr
template
thymeleaf
transaction
validation
web
webservices
websocket

如何创建自己的配置?

不知道,从来不需要这样做。但是 this blog 是一个很好的起点。