【问题标题】:What is the use of @EnableWebFlux annotation?@EnableWebFlux 注解有什么用?
【发布时间】:2020-03-19 22:46:07
【问题描述】:

我只是不明白@EnableWebFlux 的真正需求是什么。因为,我能够编写一个简单的“helloworld”WebFlux REST API,并且能够向控制器发送请求,而无需使用该注释。

我已经查看了文档,但我不清楚。

【问题讨论】:

  • 我知道 stackoverflow 中有类似的问题。但它没有回答我的问题。谢谢!
  • 什么 具体不清楚?
  • 文档:“将此注释添加到 @Configuration 类会从 WebFluxConfigurationSupport 导入 Spring WebFlux 配置,从而可以使用带注释的控制器和功能端点”。但是带注释的控制器(@Controller)即使没有它也可以工作,对吗?还有他们所说的功能端点是什么意思?

标签: spring-boot spring-webflux


【解决方案1】:

如果你使用spring-boot-starter-webflux,配置会通过ReactiveWebServerFactoryAutoConfigurationWebFluxAutoConfiguration自动完成,所以你不需要@EnableWebFlux

当您使用spring-webflux 而不使用spring-boot 时,您需要在@Configuration 类上添加@EnableWebFlux 以从WebFluxConfigurationSupport 导入Spring WebFlux 配置

【讨论】:

    【解决方案2】:

    Spring boot 使用自动配置机制,它基于项目的依赖项(类路径)为您创建默认配置。因此,当您的类路径中有 spring-boot-starter-webflux 时,spring boot 自动配置机制会自动创建该模块工作所需的所有 bean。这就是您的@Controller 开箱即用的原因。

    您的项目依赖于一个名为 spring-boot-autoconfigure 的模块,并且有一个 classorg.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration 这个 @Configuration 类负责自动配置 webflux 模块。但是当满足其他条件(由@ConditionalOn... 注释表示)时,此@Configuration 有效。

    @Configuration(proxyBeanMethods = false)
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
    @ConditionalOnClass(WebFluxConfigurer.class)
    @ConditionalOnMissingBean({ WebFluxConfigurationSupport.class })
    @AutoConfigureAfter({ ReactiveWebServerFactoryAutoConfiguration.class, CodecsAutoConfiguration.class,
            ValidationAutoConfiguration.class })
    @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
    public class WebFluxAutoConfiguration { ...
    

    @EnableWebFlux 只导入DelegatingWebFluxConfiguration

    @Import(DelegatingWebFluxConfiguration.class)
    public @interface EnableWebFlux {
    }
    

    和这个类 WebFluxConfigurationSupport 的一个子类,它检测 并委托给所有 WebFluxConfigurer 类型的 bean,允许它们 自定义 WebFluxConfigurationSupport 提供的配置。 这是@EnableWebFlux 实际导入的类。

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多