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

Viewed 508

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?

2 Answers

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

}

You can definetely make a custom constructor that takes the argument as String and does your custom logic:

@SpringBootApplication
public class ConsoleApp implements CommandLineRunner {


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

    public ConsoleApp(@Value("${numberOfDocs:10}") String numberOfDocuments){
        try{
            this.numberOfDocuments=Integer.parseInt(numberOfDocuments);
        }catch(NumberFormatException e){
            this.numberOfDocuments=10;
        }
    }

}

Note that I have removed the lombok @RequiredArgsConstructor because I used a custom constructor.

Related