javaspring-bootcontrollerprefix

Add prefix to some java spring boot controllers


Is there a way to add a prefix to a group od controllers leaving the rest of the controllers out of this prefix example:

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(value = "/families")
@RolesGuard(role = {Roles.Manager, Roles.Employee})
public class MyController {
    ...
}

I already added the global prefix for the whole app using context-path but I want a custom prefix for this controller and the other controllers of same package without affecting the rest of the controllers without adding @RequestMapping(value = "/prefix/families") for example for every controller knowing that my controllers are grouped according to their functionality into several package (products, suppliers, ...)


Solution

  • I solved this by a solution as simple as a 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) {
            
        }
    }
    
        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.