【问题标题】:Don't spring-boot-starter-web and spring-boot-starter-webflux work together?spring-boot-starter-web 和 spring-boot-starter-webflux 不能一起工作吗?
【发布时间】:2018-12-24 22:29:10
【问题描述】:

当我开始学习spring-webflux时,我对这个组件有疑问。

我建立了一个简单的项目,使用 maven 来管理它。我添加了与spring-boot-starter-webspring-boot-starter-webflux 相关的依赖项,例如:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

但它不起作用。去掉spring-boot-starter-web依赖后,就可以正常工作了。

【问题讨论】:

  • 它们是互斥的,你要么使用 webflux (reactive API) 要么使用 web (Servlet API)

标签: java spring-boot spring-webflux


【解决方案1】:

the Spring Boot reference documentation section about WebFlux 中所述,添加 web 和 webflux 启动器将配置 Spring MVC Web 应用程序。

这是这样的,因为许多现有的 Spring Boot Web 应用程序(使用 MVC)将依赖于 webflux starter 来使用 WebClient。 Spring MVC partially support reactive return types,所以这是一个预期的用例。反之则不然,因为响应式应用程序不太可能使用 Spring MVC 位。

因此同时使用 web 和 webflux 启动器是支持的,但它会配置一个 Spring MVC 应用程序。您始终可以强制 Spring Boot 应用程序响应:

SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)

但清理依赖项仍然是一个好主意,因为在您的响应式 Web 应用程序中使用阻塞功能很容易。

【讨论】:

  • 谢谢,明白了。
【解决方案2】:

我在使用 spring-boot-starter-webfluxspring-data-geode 时遇到了类似的问题

DEBUG [http-nio-8082-exec-2] org.sprin.web.servl.resou.ResourceHttpRequestHandler 454 handleRequest: Resource not found

已通过更改应用程序类型解决

@SpringBootApplication
public class Web {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Web.class);
        app.setWebApplicationType(WebApplicationType.REACTIVE);
        SpringApplication.run(Web.class, args);
    }
}

整个班级是这样的

设置应用程序类型后,如果我不以静态方式调用SpringApplication,我会得到:

【讨论】:

  • 你确定你解决了什么问题吗?因为您声明的 app 变量实际上是无用的,因为您以传统方式运行 Spring Boot 应用程序(最后一行)...
  • 看起来你是对的,它看起来应该是app.run,但可能是因为SpringApplication.run 采用Web.class 类,这是app 所在类的名称定义,它使用它而不是默认值。我编辑了上面的代码。
  • 这不会改变任何东西;将webApplicationType 设置为SpringApplication.run() 未使用的变量是没有用的。 SpringApplication.run() 是一个静态方法,所以一旦 Java 运行它,app 变量就会丢失...
  • 我用我看到的内容再次更新了这个问题,是的...哎呀...除了春天run 至少指的是Web.class 你确定吗?
  • SpringApplication.run(Web.class, args); 其中Web.class 是声明SpringApplication app 类型为REACTIVE 的类的名称,它可以工作...so don't fix it?!
猜你喜欢
  • 2019-10-28
  • 2017-03-23
  • 1970-01-01
  • 2020-07-02
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
  • 2017-02-19
相关资源
最近更新 更多