What are the recommended approac开发者_运维知识库hes for generating routes in a java-based Spring MVC webapp? I'd like to avoid hard-coding paths throughout the application.
Assuming we are talking about paths RequestMappings etc.
In my application I have a single class with with a bunch of public static final
constants that I reference in the @RequestMapping annotations.
So the constants might look like this:
public class Pages {
public static final String FOO_URL "foo/foo.action"
public static final String FOO_VIEW "test/foo"
public static final String BAR_URL "bar/bar.action"
public static final String BAR_VIEW "test/bar"
}
then inside your controller you'd reference them like this:
@RequestMapping(value=Pages.FOO_URL, method=RequestMethod.GET)
public String handleFoo(Model model) {
return Pages.FOO_VIEW;
}
They're easy to change as they're all in one place.
You say you'd like to avoid hard-coding paths throughout the application, but typically all the controllers (and thus all the url mappings) reside in one directory. For example if you have a maven structure they'll be someplace like src/main/java/com/mycompany/myapp/web/controllers/. Do you envision yourself ever asking the question, "Just where did I put the url mapping for the /myapp/v1/search endpoint?", and not being able to figure out that it's in /src/main/java/com/mycompany/myapp/web/controllers/V1SearchController.java?
Also once you choose the urls they're pretty much fixed since they represent an interface with clients, and changing them probably means breaking backward compatibility.
Not that I think a class with a bunch of static final Strings is all that bad, I just think it's mostly unnecessary.
精彩评论