Should I use an enumeration instead?
You can not. Annotation variables must be compile time constants. Speech and string literals are both, but you cannot create an enumeration that is a string, and @RequestMapping requires a string (and if your enumeration has a method that returns a String or String field, this is not a compile time constant). Since there are several rounds of processing annotations, it works when the constant is in another class.
That said: yes, I would say using a special class of constants (maybe a few for different types of constants) is a good practice that I use whenever I can (and it works with annotations until constant a) is defined inside the same compilation unit that has the annotation, and b) is initialized in the declaration (as opposed to the static initializer block)).
Here is an example:
controller
@Controller @RequestMapping(value = Mappings.CUSTOMER_PAGE) public class CustomerPageController{
Class of constants
public static final class Mappings{ private Mappings(){} public static final String CUSTOMER_PAGE = "path/to/customer/page"
And here are some versions that will not work:
but)
@Controller @RequestMapping(value = CUSTOMER_PAGE) public class CustomerPageController{ private static final String CUSTOMER_PAGE = "path/to/customer/page"; }
This will not compile because the annotation refers to a constant inside the class that it is commenting on. This will not work, because during compilation, annotations are processed in a separate round to the rest of the code, while the class needs an annotation to process already for compilation (i.e. there is an exact relationship between the annotation and constant)
b)
public static final class Mappings{ private Mappings(){} public static final String CUSTOMER_PAGE; static{ CUSTOMER_PAGE = "path/to/customer/page" }
Although this is a static final field, it is not a compile-time constant, so it cannot be used as an annotation parameter
Sean Patrick Floyd
source share