Don’t forget to set the retention to runtime, otherwise the annotation won’t be available. Now it’s time to define how we want to resolve the argument annotated with @Country. The HandlerAdapter takes care of this resolution but it delegates to the WebArgumentResolvers for this task. We’ll implement our custom WebArgumentResolver:

As you can see, it’s quite straightforward, we just need to implement a single method. What this resolver is doing, is basically checking if the parameter is annotated with @Country, getting the user IP and calling a web service to get geolocalization data of the user IP (notice that an extra class has been created, UserInfo, in order to bind the web service parameters). I’ll be using IPInfoDB as the geolocalization service.

We just have one step left: define our new resolver in the handler adapter. Our custom web argument resolver will kick in before any Spring MVC default resolver.

@RequestMapping(value="/", method=RequestMethod.GET)
public String home(@Country String userCountry, Model model) {
String message = null;
if(userCountry.equals("SPAIN")) {
message = "It seems you are in the same country as I am, up for a beer?";
} else {
message = "It seems we are not close to each other, will let you know when I am in " + userCountry;
}
model.addAttribute("message", message);
return "home";
}