我想为id ->实体使用一个自定义的WebArgumentResolver。如果我使用请求参数就很容易:使用参数键来确定实体类型并进行相应的查找。
但我希望它像@PathVariable注释一样。
例如:
http://mysite.xzy/something/enquiryId/itemId将触发此方法
@RequestMapping(value = "/something/{enquiry}/{item}")
public String method(@Coerce Enquiry enquiry, @Coerce Item item) @强制注解会告诉WebArgumentResolver根据它的类型使用特定的服务。
问题是找出哪个uri部分属于实体。
有人能解释一下PathVariable注解是怎么做到的吗?有没有可能用我的自定义注解来模拟它。
谢谢。
发布于 2011-03-12 07:45:10
您可以使用@InitBinder 让spring知道如何将给定的字符串强制转换为您的自定义类型。
你可能需要这样的东西:
@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));
        }
    });
}发布于 2012-05-18 03:26:37
对于不需要为每个实体指定一个PropertyEditor的通用方法,可以使用ConditionalGenericConverter:
public final class GenericIdToEntityConverter implements ConditionalGenericConverter {
    private static final Logger log = LoggerFactory.getLogger(GenericIdToEntityConverter.class);
    private final ConversionService conversionService;
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    public GenericIdToEntityConverter(ConversionService conversionService) {
        this.conversionService = conversionService;
    }
    public Set<ConvertiblePair> getConvertibleTypes() {
        return ImmutableSet.of(new ConvertiblePair(Number.class, AbstractEntity.class),
                new ConvertiblePair(CharSequence.class, AbstractEntity.class));
    }
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
        return AbstractEntity.class.isAssignableFrom(targetType.getType())
        && this.conversionService.canConvert(sourceType, TypeDescriptor.valueOf(Long.class));
    }
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (source == null) {
            return null;
        }
        Long id = (Long) this.conversionService.convert(source, sourceType, TypeDescriptor.valueOf(Long.class));
        Object entity = entityManager.find(targetType.getType(), id);
        if (entity == null) {
            log.info("Did not find an entity with id {} of type {}", id,  targetType.getType());
            return null;
        }
        return entity;
    }
}https://stackoverflow.com/questions/5060589
复制相似问题