是否可以使用一组预定义的参数创建与 Spring MVC @RequestMapping 等效的 Java 注解?
例如,一些允许我简单使用的东西:
@PostJson("/input")
public Output myMethod(Input input) {
代替:
@RequestMapping(value = "/input",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public Output myMethod(Input input) {
更新: 让我尝试更深入地挖掘一下。 AFAIK,Spring 似乎能够在扫描 bean 时处理元注释。例如,如果我创建一个注解,假设是@MyComponent,并用@Component 对其进行注解:
@Component
public @interface MyComponent {
String value() default "";
}
Spring 似乎能够使用@MyComponent 找到bean 并识别@MyComponent 中的参数(在本例中为值),就好像它们来自@Component
@MyComponent("MyBean")
public class SomeClass {
我用@RequestMapping 尝试过类似的策略
@RequestMapping(method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public @interface PostJson {
String value() default "";
}
固定参数(method an produces)似乎是正确的,然而,可变参数(value)被忽略了。
我希望这不是 @Component 特定的功能,我可以将它与 @RequestMapping 一起使用。
最佳答案
不容易,不。 @RequestMapping
注释绑定(bind)到 RequestMappingHandlerMapping
和 RequestMappingHandlerAdapter
.当您提供 <mvc:annotation-driven />
时,这是默认注册的 MVC 堆栈的两个元素或 @EnabledWebMvc
.他们只扫描 @Controller
和 @RequestMapping
, 没有别的。
要使您自己的注释起作用,您必须重写(并注册)这两个注释或从头开始创建新注释以提供处理程序方法的扫描和处理。 You can get some inspiration from those classes及其他 HandlerMapping
implementations ,但这确实不是一项简单的任务。
或者,您可能想查看 Java Restful Web Services它可以与 Spring 很好地集成(尽管不一定是 Spring MVC)。当您确切知道自己想要什么时,它可以提供一些不那么臃肿的映射注释。
关于java - 使用Spring MVC创建注解设置@RequestMapping参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26049810/