6

Is there a way to use an Enum value in a RequestMapping?

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

I want to use a URL value that is already stored in an Enum.

However, I get compile time errors when I try to put anything except a String literal in the RequestMapping.

How does it know the difference between a String literal and a String that is not a String literal ( not sure what that's called ) ?

This is what I tried but it failed at compile time:

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

I also tried using String.format but it doesn't like that either:

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

2 回答 2

1

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

于 2011-09-06T04:06:33.183 回答
0

将你的 URL 绑定到一个枚举值似乎很有趣;如果我更新了枚举,我不希望我的 URL 发生变化。您实际上是在使用这些相同的枚举生成客户端链接吗?也许相反,您可以只查询 Spring 的 Handler bean 的 URL?

还有Spring Expression Language,但我只知道它在 @Value 注释中有效,我不确定 @RequestMapping

如果您尝试以一种方法捕获多个 URL,则可以使用@PathVariable

于 2012-04-27T22:50:19.543 回答