开发者

Is it possible to use a value for a @RequestMapping that is a String but not a String literal?

开发者 https://www.devze.com 2023-04-03 00:05 出处:网络
Is there a way to use an Enum value in a RequestMapping? @RequestMapping(value = \"/example\", method = RequestMethod.POST)

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,


Only literal values can be assigned to annotation attributes because they must be known at compile-time when annotations are processed. Yes, you could use an enum value, where "enum value" is FooEnum.Example, but not on an attribute that takes a String value, and you can't call a method on it.


Tying your URL to an enum value seems funny; I wouldn't want my URLs to change if I updated the enum. Are you actually generating the client links using these same enums? Maybe instead you could just query Spring's Handler bean for the URLs?

There's also the Spring Expression Language, but I only know that it works in @Value annotations, I'm not sure about @RequestMapping

If you're trying to catch multiple URLs in one method, you could use @PathVariable

0

精彩评论

暂无评论...
验证码 换一张
取 消