Search code examples
javaspringspring-bootspring-cloud-configspring-cloud-config-server

Is there a way in which we can check for presence of data in application.properties file in Spring Boot Project before the tomcat server starts?


I am writing a Spring Boot project to Run a Cloud Config Server and 3 Micro-services to run as a Client.

I would want to check availability of all properties in application.properties or yaml file before starting the tomcat server.

We already have a similar one for Database Startup Validation, but here I am trying to achieve the same for Property file availability.

Can someone let me know or suggest possible solutions.


Solution

  • You can simply add whatever you want to add in application.properties / yaml file and then access the property and its value in SpringBoot Application like this.

    I think this could help you.

    application.properties

    property1=true
    property2=false
    property3=abc
    property5=1223243
    

    and in SpringBoot Application

    TestApplication.java

    @SpringBootApplication
    public class TestApplication{
    
        @Value("${property1}")
        private boolean property1
    
        @Value("${property2}")
        private boolean property2
    
        @Value("${property3}")
        private String property3
    
        @Value("${property5}")
        private int property5
    
        public static void main(String[] args) {
            SpringApplication.run(TestApplication.class, args);
        }
    
     }
    

    [UPDATE]

    If we are agreed to create a Pre-Script that run before tomcat startup then

    Using the following code snippet we can parse the application.properties file and create object and then loop through the length of properties file and check the Key Value pairs

    FileReader reader=new FileReader("application.properties");  
      
    Properties p=new Properties();  
    p.load(reader);  
      
    System.out.println(p.getProperty("user"));  
    System.out.println(p.getProperty("password"));