java - Spring Boot如何创建Auto配置类

标签 java spring-mvc spring-boot annotations xml-configuration

<分区>

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

我的问题是:

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

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

最佳答案

Spring Boot 核心包 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是一个很好的起点。

关于java - Spring Boot如何创建Auto配置类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46930929/

相关文章:

java - 如何根据特定键的值 null 删除 JSON 数组中的 JSON 对象?

java - 使用 <context :annotation-config/> in ApplicationContext. xml 时自动连线注释不起作用

java - Spring MVC/hibernate 表单验证,不返回表单

java - 数据源对象被 Cloud Foundry 配置覆盖

java - "Could not find class android.transition.Transition"按返回键时异常

java - 简单计数信号量

spring - spring mvc 应用程序中的 main() 方法

java - Spring boot Resttemplate动态代理设置通过ssh隧道连接无法识别远程DNS

java - 如何确保 spring boot 中方法执行的原子性?

java - 在 Jackrabbit Repository 中存档文档的最佳方式是什么?