Currently I am trying to reduce the boilerplate in my java spring controllers by creating an interface CRUDRestController
, which creates a common set of default endpoints:
interface CRUDRestController<T, Key extends Serializable> {
//...
String getEndpoint();
@RequestMapping(value = getEndpoint() + "/{key}", method = RequestMethod.GET)
default T get(@PathVariable("key") String key) {
return getRepository().findOne(stringToKey(key));
}
//...
}
The problem is that the above code does not compile since value = getEndpoint() + "/{key}"
is supposedly not a compile time constant. In reality every controller's implementation of getEndpoint()
is something like this:
@Override
public String getEndpoint() {
return "/clients";
}
This is clearly known at compile time, however I have no way of telling this to spring. Any ideas?
Maybe that will help you:
interface CRUDRestController<T, Key extends Serializable> {
@RequestMapping(value = "/{key}", method = RequestMethod.GET)
default T get(@PathVariable("key") String key) {
return getRepository().findOne(stringToKey(key));
}
}
and the implementation:
@RequestMapping("/clients")
public class ClientController implements CRUDRestController<Client, ClientKey> {
//...
}