我的 Spring Boot 應用程式中的 API 有一個Enum型別的查詢引數。從郵遞員那里,它只接受Enum字串值。當作為查詢引數值發送時,它以 400 作為整數回應。如何配置 Spring Boot 應用程式以接受列舉字串值或列舉索引/序號值作為查詢引數。
下面這兩種方式都應該作業
<base-url>/123/status?status=inprogress<base-url>/123/status?status=2(2 是進度索引enum)
我正在使用 Java,spring boot fw。它在 dotNet 中運行良好
uj5u.com熱心網友回復:
據我所知,沒有辦法通過注釋來神奇地做到這一點。你可以做的是實作一個自定義轉換器并將輸入的值轉換成你enum這樣的:
public class MyCustomEnumConverter implements Converter<String, YourEnum>
{
@Override
public YourEnum convert(String source) {
try
{
if(isNumeric(source)) // If the string passed is a Number
{
int index = Integer.parseInt(source);
return YourEnum.values()[index]; // Get the Enum at the specific index
}
// Else if it is a string..
return YourEnum.valueOf(source);
} catch(Exception e) {
return null; // or whatever you need
}
}
private static boolean isNumeric(String str) {
try {
Integer.parseInt(str);
return true;
} catch(NumberFormatException e){
return false;
}
}
}
然后注冊您的Converter:
@Configuration
public class MyConfig extends WebMvcConfigurationSupport {
@Override
public FormattingConversionService mvcConversionService() {
FormattingConversionService f = super.mvcConversionService();
f.addConverter(new MyCustomEnumConverter());
return f;
}
}
你可以改進邏輯,MyCustomEnumConverter但為了簡單起見,我把它留在了那里。
如果您只想將特定應用應用于Converter一個控制器,請檢查此答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/313594.html
上一篇:使用oracle引數系結變數
