4

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 2

6

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; } } } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.