如何在Spring-Boot中捕获属性的NumberFormatException?
我有以下财产:
@RequiredArgsConstructor
@SpringBootApplication
public class ConsoleApp implements CommandLineRunner {
@Value("${numberOfDocs:10}")
private int numberOfDocuments;
如果我的用户不顾所有警告和说明,决定在 application.properties 中为此变量放置一个非整数值,有没有办法捕获 NumberFormatException ?
我不能只是在这个变量周围放置一个 try-catch 块。那么我的其他选择是什么?
回答
您还可以使用 @Value 作为参数与 setter 注入:
@SpringBootApplication
public class ConsoleApp implements CommandLineRunner {
private int numberOfDocuments;
@Autowired
public void setValues(@Value("${numberOfDocs:10}") String numberOfDocuments) {
try this.numberOfDocuments=Integer.parseInt(numberOfDocuments);
} catch(NumberFormatException e){
this.numberOfDocuments=10;
}
}
}
THE END
二维码