我有一个带有 @RequestMapping
注释方法的 Spring1 @Controller
注释类。我想从另一个类中引用 @RequestMapping
参数、value
和 method
的值,而不是将它们硬编码到注释中。
例子
代替
@Controller
public class MyController {
@RequestMapping(value="my/path", method=RequestMethod.GET)
public String handlePath() {
// etc...
}
}
我想要两个文件,
@Controller
public class MyController {
@RequestMapping(value=Constants.PATH, method=Constants.PATH_METHOD)
public String handlePath() {
// etc...
}
}
和
public class Constants {
public static final String PATH = "my/path";
public static final RequestMethod PATH_METHOD = RequestMethod.GET;
}
不幸的是,此操作失败并出现以下编译时错误:
error: an enum annotation value must be an enum constant
@RequestMapping(value=Constants.PATH, method=Constants.PATH_METHOD)
^
问题
为什么这对 String
有效,但对 enum
无效?
注意事项
- 这个问题不是 Spring 特有的,这只是这个问题的一个(希望)可访问的示例。
- 我碰巧在使用 Java 8
最佳答案
我们需要看看Java语言规范是怎么说的an acceptable value for an annotation method .
It is a compile-time error if the element type is not commensurate with the element value. An element type
T
is commensurate with an element valueV
if and only if one of the following is true:
- If
T
is a primitive type orString
, thenV
is a constant expression (§15.28).- If
T
is anenum
type (§8.9), then V is anenum
constant (§8.9.1).
PATH_METHOD
不是 enum
constant . RequestMethod.GET
是一个 enum
常量。对于 String
,这
public static final String PATH = "my/path";
是常量变量,是常量表达式,因此可以使用。
即使在同一个文件中声明了常量,它也不应该起作用。请检查。
关于java - 编译器说注释的 "value must be a constant",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26853644/