选项 1:自定义注释
创建一个自定义注释来声明基本 URL 并使用它来代替 @RestController。
CustomRestControllerAnnotation.java
package com.example.stackoverflow.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@RestController
@RequestMapping("/rest")
public @interface CustomRestControllerAnnotation {}
FirstRestController.java
package com.example.stackoverflow.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.stackoverflow.config.CustomRestControllerAnnotation;
@CustomRestControllerAnnotation
public class FirstRestController {
@RequestMapping("/first")
public String firstMethod(){
return "First Controller";
}
}
SecondRestController.java
package com.example.stackoverflow.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.stackoverflow.config.CustomRestControllerAnnotation;
@CustomRestControllerAnnotation
public class SecondRestController {
@RequestMapping("/second")
public String secondMethod(){
return "Second Controller";
}
}
选项 2:基本 RestController
通过创建一个用作所有实际控制器模板的基本控制器,您可以从一个位置有效地管理根 URL。
BaseRestController.java
package com.example.stackoverflow.controller;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/rest")
public class BaseRestController {}
然后,您只需为所有实际控制器扩展此类。
FirstRestController.java
package com.example.stackoverflow.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FirstRestController extends BaseRestController{
@RequestMapping("/first")
public String firstMethod(){
return "First Controller";
}
}
SecondRestController.java
package com.example.stackoverflow.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SecondRestController extends BaseRestController{
@RequestMapping("/second")
public String secondMethod(){
return "Second Controller";
}
}
选项 3:Spring Data REST
如果您的控制器从存储库提供数据,那么 Spring Data REST 可以消除大部分样板文件并解决您最初的问题。
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
通过声明此依赖关系,您的所有存储库都会自动启用 REST。
您可以使用属性文件来控制基本 URL。
application.properties
spring.data.rest.basePath=/rest