문제

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가 IT 유형을 기반으로 특정 서비스를 사용하도록 WebArgumentResolver에 알려줍니다.

문제가 엔티티에 속하는 URI 부분이 작동하는지 꺼냅니다.

누군가가 PathVariable Annotation이 어떻게 작동하는지 설명 할 수 있습니다.내 사용자 정의 주석으로 에뮬레이트 할 수 있습니다.

감사합니다.

도움이 되었습니까?

해결책

You can use @InitBinder to let spring know how to coerce a given String to your custom type.

You'd want something like:

@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));
        }
    });
}

다른 팁

For a generic approach where you don't need to specify one PropertyEditor for each entity you could use a 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;
    }

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top