简体   繁体   中英

JAX-RS and MVC at Spring Boot

I have a Spring Boot application which works as MVC. I would like to use JAX-RS at my application without using Spring annotations. I'll have both JAX-RS annotated components and MVC components at different classes. When I add a Jersey Resource Config (without registering any endpoint):

@Component
public class JerseyConfig extends ResourceConfig {

}

I startup the application and login page is not shown. Its been downloaded as like a document when I open login page. How can I solve it?

1) Make sure your app's Spring Boot configuration file makes a distinction between Spring MVC, for actuator endpoints for instance and Jersey for resources endpoints:

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) Make sure your Spring Boot app scans for components located in specific packages (ie com.asimio.jerseyexample.config) via:

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

3) Jersey configuration class implementation:

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

A more detailed how-to could be found at a blog I created a few months ago, Microservices using Spring Boot, Jersey Swagger and Docker

Probably you can add path mapping to separate REST resources, by default 'jerseyServlet' mapped to [/*], to change that to /myrest

@Configuration
@ApplicationPath("/myrest")
public class JerseyConfig extends ResourceConfig {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM