[英]Add prefix or suffix to the GET,PUT,POST,DELETE mappings in controller at method level using custom annotation - Spring REST Controller
我正在嘗試在 GET、POST、PUT、DELETE 映射之上的方法級別的控制器中添加前綴或后綴。
控制器類
@RestController
@RequestMapping("/something")
public class SomeController {
@PutMapping("/some/path/")
public ResponseEntity<ApiResponse<String>> someMethod() {
....
}
...
}
所以,基本上,上面的請求 URL 應該是這樣的: http://localhost:8080/something/some/path/
現在,我只想為請求 URL 添加一些可行的前綴或后綴,例如: http://localhost:8080/something/read/some/path/或http://localhost:8080/something /some/path/read/額外的“/read”,需要作為前綴或后綴添加到請求 URL。 我可以通過將其添加到 PutMapping 值來直接執行此操作,但我想使用@Read之類的注釋對其進行一些裝飾
所以,更新后的 Controller 類會像
@RestController
@RequestMapping("/something")
public class SomeController {
@Read
@PutMapping("/some/path/")
public ResponseEntity<ApiResponse<String>> someMethod() {
....
}
...
}
同樣的方式更新的請求 URL 將類似於: http://localhost:8080/something/read/some/path/
我無法找到更好的方法來做到這一點。 到目前為止,我只實現了使用自定義注釋添加類級前綴。
有人可以幫忙解決上述要求嗎? 謝謝 !!
我也很想知道是否可以實現?
使用這種路徑擴展方式會使您的代碼難以理解。 (也許你應該閱讀更多關於 RESTful API 的內容)但是 spring 幾乎可以做任何你想做的事情。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.stream.Stream;
@SpringBootApplication
public class DemoApplication {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Read {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Write {
}
@Bean
public WebMvcRegistrations webMvcRegistrations() {
return new WebMvcRegistrations() {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new RequestMappingHandlerMapping() {
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
RequestMappingInfo defaultRequestMappingInfo = super.getMappingForMethod(method, handlerType);
if (defaultRequestMappingInfo == null) {
return null;
}
String pathSuffix;
if (method.isAnnotationPresent(Read.class)) {
pathSuffix = "read";
} else if (method.isAnnotationPresent(Write.class)) {
pathSuffix = "write";
} else {
return defaultRequestMappingInfo;
}
//extend path by mutating configured request mapping info
RequestMappingInfo.Builder mutateBuilder = defaultRequestMappingInfo.mutate();
mutateBuilder.paths(
defaultRequestMappingInfo.getPatternValues().stream()
.map(path -> path + "/" + pathSuffix)
.toArray(String[]::new)
);
return mutateBuilder.build();
}
};
}
};
}
@RestController
@RequestMapping("/books")
public static class BooksController {
@Read
@GetMapping("/{id}")
public String readBook(@PathVariable("id") String bookId) {
return bookId;
}
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
擴展點在這里,您可以隨意更改路徑。
例子:
請求:http://localhost:8080/books/asd
回復:404
輸出:
2022-06-27 10:49:48.671 DEBUG 8300 --- [nio-8080-exec-2] com.example.demo.DemoApplication$1$1 : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
請求:http://localhost:8080/books/asd/read
回復:asd
輸出:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.0)
2022-06-27 10:48:53.622 INFO 8300 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 1.8.0_312 on DESKTOP with PID 8300 ()
2022-06-27 10:48:53.624 DEBUG 8300 --- [ main] com.example.demo.DemoApplication : Running with Spring Boot v2.7.0, Spring v5.3.20
2022-06-27 10:48:53.625 INFO 8300 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to 1 default profile: "default"
2022-06-27 10:48:54.227 INFO 8300 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-06-27 10:48:54.233 INFO 8300 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-06-27 10:48:54.233 INFO 8300 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-06-27 10:48:54.298 INFO 8300 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-06-27 10:48:54.298 INFO 8300 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 643 ms
2022-06-27 10:48:54.473 DEBUG 8300 --- [ main] com.example.demo.DemoApplication$1$1 : 3 mappings in 'requestMappingHandlerMapping'
2022-06-27 10:48:54.536 INFO 8300 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-06-27 10:48:54.543 INFO 8300 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 1.199 seconds (JVM running for 1.827)
2022-06-27 10:49:01.196 INFO 8300 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-06-27 10:49:01.196 INFO 8300 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-06-27 10:49:01.197 INFO 8300 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2022-06-27 10:49:01.210 DEBUG 8300 --- [nio-8080-exec-1] com.example.demo.DemoApplication$1$1 : Mapped to com.example.demo.DemoApplication$BooksController#readBook(String)
依賴關系
org.springframework.boot:spring-boot-starter-web
應用程序屬性
logging.level.com.example.demo=debug
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.