springspring-bootspring-mvcjerseyservlet-filters

How to use Jersey and MVC together In SpringBoot?


Let's consider a SpringBoot 2+ web application.

There are several legacy endpoints written in Jersey. All new endpoints are supposed to be defined using Spring MVC.

Since the Jersey endpoints can't be transformed instantly to MVC, I'm looking for a way to do that transition smoothly:

  1. keep both Jersey and MVC endpoints in the application
  2. preserve unchanged all URL paths pointing to Jersey endpoints
  3. make minimal intrusion into new MVC endpoints paths

The most popular way to keep Jersey and MVC together discussed in the internet guides mention usage of @ApplicationPath for Jersey config

@Configuration
@ApplicationPath("/special/prefix")
class JerseyConfig extends ResourceConfig {
    ...
}

Unfortunately that lead to using "/special/prefix" for every Jersey endpoint path, which contradicts with the intention #2 (preserve unchanged URL paths...).

Would be great to do the opposite: define special path prefix for Spring MVC endpoints or maybe even more elegant approach (e.g. using headers for routing to MVC), and keep Jersey paths as is - like "default paths without prefixes".

What is the standard way with minimal configuration to route to Jersey endpoints by default and - if not found - then route to Spring MVC endpoints?


Solution

  • application.properties

    spring.mvc.servlet.path=/mvc/prefix
    

    JerseyConfig.java (standard Jersey configuration)

    @Configuration
    @ApplicationPath("/")  // this is optional; by default (path == "/") if @ApplicationPath is absent
    class JerseyConfig extends ResourceConfig {
    
        JerseyConfig() {
            packages("my.example.jersey", "other.package"); // recursive scan
        }
    }
    

    Optionally we can add a property setting global common prefix for all endpoints server.servlet.context-path=/global/api/prefix.