Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify prefix for all controllers in Spring Boot?

I have controller mappings to /user and /order:

@RestController @RequestMapping("/users") public class UserController {     ... }  @RestController @RequestMapping("/orders") public class OrderController {     ... } 

I want to access these by URL at http://localhost:8080/api/users and http://localhost:8080/api/orders, respectively.

How do I achieve this in Spring Boot?

like image 708
Murali Avatar asked Jan 18 '15 02:01

Murali


People also ask

How do I change the prefix on a spring boot?

Then, we only need to apply the annotation to each controller we want to prefix: @Controller @ApiPrefixController public class SomeController { @RequestMapping("/users") @ReponseBody public String getAll(){ // ... } }

How does Spring Boot identify controller?

@Controller annotation indicates that the annotated class is a controller. It is a specialization of @Component and is autodetected through classpath scanning. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation.


1 Answers

You can provide a mapping to root context path of your spring boot application to /api/* in your custom configuration.

import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration; import org.springframework.boot.context.embedded.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.DispatcherServlet;  @Configuration public class DispatcherServletCustomConfiguration {      @Bean     public DispatcherServlet dispatcherServlet() {         return new DispatcherServlet();     }      @Bean     public ServletRegistrationBean dispatcherServletRegistration() {         ServletRegistrationBean registration = new ServletRegistrationBean(                 dispatcherServlet(), "/api/");         registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);         return registration;     } } 

or add this to your application.properties in src\main\resources folder

server.contextPath=/api/* 

EDIT

As of Spring Boot 2.x the property has been deprecated and should be replaced with

server.servlet.contextPath=/api/* 

More you find here Spring Boot Context Root and here Add servlet mapping to DispatcherServlet

like image 149
Tomasz Janek Avatar answered Sep 24 '22 23:09

Tomasz Janek