arm*_*mel 4 java numberformatexception spring-boot
我有以下财产:
@RequiredArgsConstructor
@SpringBootApplication
public class ConsoleApp implements CommandLineRunner {
@Value("${numberOfDocs:10}")
private int numberOfDocuments;
Run Code Online (Sandbox Code Playgroud)
如果我的用户不顾所有警告和说明,决定在 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |