gpt4 book ai didi

java - Spring Boot 中的 JAX-RS 和 MVC

转载 作者:行者123 更新时间:2023-11-30 10:38:12 28 4
gpt4 key购买 nike

我有一个作为 MVC 工作的 Spring Boot 应用程序。我想在不使用 Spring 注释的情况下在我的应用程序中使用 JAX-RS。我将在不同的类中同时使用 JAX-RS 注释组件和 MVC 组件。当我添加 Jersey 资源配置时(没有注册任何端点):

@Component
public class JerseyConfig extends ResourceConfig {

}

我启动了应用程序,但未显示登录页面。当我打开登录页面时,它就像一个文档一样被下载了。我该如何解决?

最佳答案

1) 确保您的应用程序的 Spring Boot 配置文件在 Spring MVC 和资源端点 Jersey 之间做出区分:

application.yml

...
# Spring MVC dispatcher servlet path. Needs to be different than Jersey's to enable/disable Actuator endpoints access (/info, /health, ...)
server.servlet-path: /
# Jersey dispatcher servlet
spring.jersey.application-path: /api
...

2)确保您的 Spring Boot 应用通过以下方式扫描位于特定包(即 com.asimio.jerseyexample.config)中的组件:

@SpringBootApplication(
scanBasePackages = {
"com.asimio.jerseyexample.config", "com.asimio.jerseyexample.rest"
}
)

3) Jersey配置类实现:

package com.asimio.jerseyexample.config;
...
@Component
public class JerseyConfig extends ResourceConfig {

...
public JerseyConfig() {
// Register endpoints, providers, ...
this.registerEndpoints();
}

private void registerEndpoints() {
this.register(HelloResource.class);
// Access through /<Jersey's servlet path>/application.wadl
this.register(WadlResource.class);
}
}

4) 使用 JAX-RS 的资源实现( Jersey ):

package com.asimio.jerseyexample.rest.v1;
...
@Component
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class HelloResource {

private static final Logger LOGGER = LoggerFactory.getLogger(HelloResource.class);

@GET
@Path("v1/hello/{name}")
public Response getHelloVersionInUrl(@ApiParam @PathParam("name") String name) {
LOGGER.info("getHelloVersionInUrl() v1");
return this.getHello(name, "Version 1 - passed in URL");
}
...
}

可以在我几个月前创建的博客中找到更详细的操作方法,Microservices using Spring Boot, Jersey Swagger and Docker

关于java - Spring Boot 中的 JAX-RS 和 MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39828672/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com