How to set base url for rest in spring boot?

后端 未结 18 2368
日久生厌
日久生厌 2020-11-28 03:23

I\'m trying to to mix mvc and rest in a single spring boot project.

I want to set base path for all rest controllers (eg. example.com/api) in a single place (I don\'

18条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 03:58

    I couldn't believe how complicate the answer to this seemingly simple question is. Here are some references:

    • Spring JIRA Ticket
    • Another SO question
    • Yet another SO question
    • Very nice GitRepository that showcases the problem

    There are many differnt things to consider:

    1. By settingserver.context-path=/api in application.properties you can configure a prefix for everything.(Its server.context-path not server.contextPath !)
    2. Spring Data controllers annotated with @RepositoryRestController that expose a repository as rest endpoint will use the environment variable spring.data.rest.base-path in application.properties. But plain @RestController won't take this into account. According to the spring data rest documentation there is an annotation @BasePathAwareController that you can use for that. But I do have problems in connection with Spring-security when I try to secure such a controller. It is not found anymore.

    Another workaround is a simple trick. You cannot prefix a static String in an annotation, but you can use expressions like this:

    @RestController
    public class PingController {
    
      /**
       * Simple is alive test
       * @return 
    {"Hello":"World"}
    */ @RequestMapping("${spring.data.rest.base-path}/_ping") public String isAlive() { return "{\"Hello\":\"World\"}"; } }

提交回复
热议问题