是否可以使用@RequestMapping的值,该值是String而不是String文字?

Pit*_*den 5 java enums spring-mvc string-literals

有没有办法在RequestMapping中使用Enum值?

@RequestMapping(value = "/example", 
method = RequestMethod.POST)
public final void foo(final HttpServletResponse response,
Run Code Online (Sandbox Code Playgroud)

我想使用已存储在枚举中的URL值.

但是,当我尝试将除字符串文字之外的任何内容放入其中时,我会收到编译时错误RequestMapping.

它是如何知道字符串文字和不是字符串文字的字符串之间的区别(不确定是什么叫)?

这是我尝试过但在编译时失败了:

@RequestMapping(value = FooEnum.Example.getStringValue(), 
method = RequestMethod.POST)
public final void foo(final HttpServletResponse response,
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用,String.format但它不喜欢这样:

@RequestMapping(value = String.format("%s", FooEnum.Example.getStringValue()), 
method = RequestMethod.POST)
public final void foo(final HttpServletResponse response,
Run Code Online (Sandbox Code Playgroud)

Rya*_*art 1

只能将文字值分配给注释属性,因为在处理注释时必须在编译时知道它们。是的,您可以使用枚举值,其中“枚举值”是FooEnum.Example,但不能在采用 String 值的属性上使用,并且您不能对其调用方法。

  • 不仅仅是文字值,而是常量(在编译时)值,甚至是诸如“PO”+“ST”之类的表达式,只要它们计算结果为常量。这就是为什么“RequestMethod.POST”是注释中的有效属性值,但方法调用却不是。 (2认同)