JavaEE |
Blogs

Build web services with different upper root path using Jersey + Spring boot

In a servlet container, the Jersey runtime, runs as either a servlet or as a servlet filter. How spring boot configures servlets and filters is through ServletRegistrationBeans and FilterRegistrationBeans, respectively. To get an idea of how that configuration works behind scenes, you can look at the source code for the JerseyAutoConfiguration

In the JerseyAutoConfiguration, you can see that a ResourceConfig is injected, and that is the ResourceConfig used to create the Jersey servlet or Jersey filter (depending on your choice of configuration). So the reason for the error is that you can’t have ambiguous beans, which you have two ResourceConfig beans. So Spring doesn’t know which one to inject.

Why we use ResourceConfig and not Application for webservice configuration

Compared to Application, the ResourceConfig provides advanced capabilities to simplify registration of JAX-RS components, such as scanning for root resource and provider classes in a provided classpath or a set of package names etc. All JAX-RS component classes that are either manually registered or found during scanning are automatically added to the set of classes that are returned by getClasses. For example, the following application class that extends from ResourceConfig scans during deployment for JAX-RS components in packages org.foo.rest and org.bar.rest:

What you can do though, is use two different servlets for each ResourceConfig. The problem is that Spring Boot only hooks you up with one servlet for Jersey, so you need to configure the other one yourself. There are two options:

Option 01 :

Use the Spring Boot auto-configuration for one of the Jersey applications.


And add another ServletRegistrationBean for your other one. The one thing to note is that the ResourceConfig for your created ServletRegistrationBean should not be a Spring component (i.e. no @Component or @Configuration), or else you will still face the same error.

Option 02 :

Don’t use the Spring Boot configuration at all. Just create two ServletRegistrationBeans. In this case, none of your ResourceConfig classes should be Spring beans.

Personally, I prefer the second option, as it is easier to reason about the configurations when they are all in one place.

Another thing to note is that the two Jersey applications will be completely independent, meaning you will need to register providers (like filters) for both applications

Source code : https://github.com/salahtobok/spring-webcodein/tree/main/webcodein-admin/src/main/java/com/webcodein/admin/config/webservice

Resource : Stackoverflow, ChatGPT, Bard, Jersey .

Comments

You must be Login in to post a comment.

Related Posts