2016-12-16 3 views
1

すべてのRESTfulメソッド(> 50)の受信IDパラメータを検証したいとします。Spring MVCは、特定のパラメータオブジェクトのすべてのマッピングに常に@Validを適用します。

私が持っている例として:

@RequestMapping(
     value = "/{id}", 
     method = RequestMethod.GET, 
     produces = {"application/json"}) 
@ResponseStatus(HttpStatus.OK) 
public 
@ResponseBody 
Metadata getMetadata(
     @PathVariable("id") Long id, 
     HttpServletRequest request, 
     HttpServletResponse response) throws Exception { 

    return metadataService.get(id); 
} 

私はID < 1.場合は、私が実装しました解決策として、すべての要求を拒否したいと思います:

@RequestMapping(
     value = "/{id}", 
     method = RequestMethod.GET, 
     produces = {"application/json"}) 
@ResponseStatus(HttpStatus.OK) 
public 
@ResponseBody 
Metadata getMetadata(
     @Valid Id id, 
     HttpServletRequest request, 
     HttpServletResponse response) throws Exception { 

    return metadataService.get(id.asLong()); 
} 

public class Id { 

@Min(1) 
@NotNull 
private Long id; 

public void setId(Long id) { 
    this.id = id; 
} 

public Long asLong() { 
    return id; 
} 

} 

しかし、今、私は暗黙のうちに持っています非常に冗長に見えるId引数のためのすべてのメソッドごとに@Validアノテーションを入れてください。 Springに、着信パラメータとしてIdオブジェクトがある場合は常に@Validにする必要があることを伝える方法はありますか?注釈を毎回入れないで?

ありがとうございました。

答えて

0

だから私はこのようなソリューションになってしまってきた:それぞれ、すべての着信パラメータのクラスをチェックする

@Configuration 
@EnableWebMvc 
public class ApplicationConfig extends WebMvcConfigurerAdapter { 

    @Override 
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { 
     super.addArgumentResolvers(argumentResolvers); 
     argumentResolvers.add(new CustomModelAttributeMethodProcessor(true)); 
    } 
} 

ビットのオーバーヘッド、:

public class CustomModelAttributeMethodProcessor extends ModelAttributeMethodProcessor { 

public CustomModelAttributeMethodProcessor(boolean annotationNotRequired) { 
    super(annotationNotRequired); 
} 

@Override 
protected void bindRequestParameters(final WebDataBinder binder, final NativeWebRequest request) { 
    HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class); 
    ((ServletRequestDataBinder) binder).bind(servletRequest); 
} 

@Override 
protected void validateIfApplicable(final WebDataBinder binder, final MethodParameter parameter) { 
    if (binder.getTarget().getClass().equals(Id.class)) { 
     binder.validate(); 
     return; 
    } 

    super.validateIfApplicable(binder, parameter); 
} 

}

と設定期待どおりに動作します。 @Validアノテーションは、カスタムプロセッサによって検証が実行されるときに省略できます。

関連する問題