Search code examples
javaspring-bootnumberformatexception

How to catch a NumberFormatException for a property in Spring-Boot?


I have the following property:

@RequiredArgsConstructor
@SpringBootApplication
public class ConsoleApp implements CommandLineRunner {


    @Value("${numberOfDocs:10}")
    private int numberOfDocuments;

Is there a way to catch the NumberFormatException , if my user, in spite of all the warnings and instructions, decides to put a non-integer value for this variable in application.properties?

I can't just put a try-catch block around this variable. So what are my other options?


Solution

  • you could also use @Value as parameter with setter injection:

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