I solved this by a solution as simple as a configuration class.
- Step 1: Creat
Configuration class:
package com.example.configurations;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class PrefixConfiguration implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
}
}
- Step 2: Add path prefix using the configurer as follows:
configurer.addPathPrefix(
"/products", handler -> handler
.getPackage()
.getName()
.startsWith("com.example.products")
);
Full code will be:
package com.example.configurations;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class PrefixConfiguration implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix(
"/products", handler -> handler
.getPackage()
.getName()
.startsWith("com.example.products")
);
}
}
This will prefix all controllers in the package com.example.products with the prefix /products so the previous route /families will now be accessed as /products/families of course we can't forget the global prefix that need to be added to all endpoints.