自定义WebArgumentResolver,例如@PathVariable


问题内容

我想为ID->实体使用自定义WebArgumentResolver。如果我使用请求参数,这很容易:使用参数键确定实体类型并进行相应查找。

但我希望它就像@PathVariable注解。

例如。

http://mysite.xzy/something/enquiryId/itemId会触发此方法

@RequestMapping(value = "/something/{enquiry}/{item}")
public String method(@Coerce Enquiry enquiry, @Coerce Item item)

@Coerce批注将告诉WebArgumentResolver根据其类型使用特定的服务。

问题是确定哪个uri部分属于实体。

有人可以解释PathVariable注释是如何做到的。并可以使用我的自定义注释来模拟它。

谢谢。


问题答案:

您可以使用@InitBinder让spring知道如何将给定的String强制转换为您的自定义类型。

您想要以下内容:

@RequestMapping(value = "/something/{enquiry}")
public String method(@PathVariable Enquiry enquiry) {...}


@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Enquiry.class, new PropertyEditorSupport() {
        @Override
        public String getAsText() {
            return ((Enquiry) this.getValue()).toString();
        }

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue(new Enquiry(text));
        }
    });
}