2

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, ...)

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.