Should the displayed value be declared in constant or as an enumeration?

I see this scattered throughout the code base:

@RequestMapping(value = "myValue") 

I would rather use something like this:

 @RequestMapping(value = Constants.myValue) 

It seems to be interrupted by DRY, using the actual String value inside @RequestMapping instead of a constant. But is this practice good code? Should I use an enumeration instead? I might need to use Constants.myValue elsewhere in the code base.

+8
java spring enums spring-mvc dry
source share
1 answer

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{ // methods here } 

Class of constants

 public static final class Mappings{ private Mappings(){} public static final String CUSTOMER_PAGE = "path/to/customer/page" // more constants } 

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" } // more constants } 

Although this is a static final field, it is not a compile-time constant, so it cannot be used as an annotation parameter

+12
source share

All Articles