Spring MVC Annotated Controller Interface with @PathVariable

后端 未结 5 1617
走了就别回头了
走了就别回头了 2020-11-30 02:47

Is there any reason not to map Controllers as interfaces?

In all the examples and questions I see surrounding controllers, all are concrete classes. Is there a reaso

5条回答
  •  抹茶落季
    2020-11-30 03:48

    The feature of defining all bindings on interface actually got implement recently in Spring 5.1.5.

    Please see this issue: https://github.com/spring-projects/spring-framework/issues/15682 - it was a struggle :)

    Now you can actually do:

    @RequestMapping("/random")
    public interface RandomDataController {
    
        @RequestMapping(value = "/{type}", method = RequestMethod.GET)
        @ResponseBody
        RandomData getRandomData(
                @PathVariable(value = "type") RandomDataType type, @RequestParam(value = "size", required = false, defaultValue = "10") int size);
    }
    
    @Controller
    public class RandomDataImpl implements RandomDataController {
    
        @Autowired
        private RandomGenerator randomGenerator;
    
        @Override
        public RandomData getPathParamRandomData(RandomDataType type, int size) {
            return randomGenerator.generateRandomData(type, size);
        }
    }
    

    You can even use this library: https://github.com/ggeorgovassilis/spring-rest-invoker

    To get a client-proxy based on that interface, similarly to how RestEasys client framework works in the JAX-RS land.

提交回复
热议问题