小编典典

Spring Boot上的JAX-RS和MVC

spring-mvc

我有一个可以作为MVC使用的Spring Boot应用程序。我想在我的应用程序中使用JAX-
RS而不使用Spring注释。我将在不同的类中同时使用带有JAX-RS注释的组件和MVC组件。当我添加Jersey Resource
Config(不注册任何端点)时:

@Component
public class JerseyConfig extends ResourceConfig {

}

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


阅读 570

收藏
2020-06-01

共1个答案

小编典典

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");
    }
...
}

可以在我几个月前创建的博客中找到更详细的操作方法,该博客使用Spring Boot,Jersey
Swagger和Docker进行微服务。

2020-06-01