Search code examples
javaspring-bootproperties-file

Spring Auto Create Properties File


I have a simple class to represent property file using @PropertySource like so

@Component
@PropertySource(value = "file:${user.home}/.cooperp/app-conf.properties")
public class ApplicationProperties {
    @Value("${mysql-location}")
    private String mysqlLocation;

    public String getMysqlLocation() {
        return mysqlLocation;
    }

    public void setMysqlLocation(String mysqlLocation) {
       this.mysqlLocation = mysqlLocation;
    }
}

I know if file is not found one can add ignoreResourceNotFound = true which will make spring to ignore its absence and startup the application.

I would like spring to create the file it not found, not ignore or throw exception.


Solution

  • Usually we keep the properties file withing the project directory. But if your project requires the properties outside then you can check if the file exists in SpringBootApplication class. If it doesen't, then you can create the properties file there. Code example :

    @SpringBootApplication
    public class SpringDocBotApplication {
    
        public static void main(String[] args) {
            File file = new File("EXPECTED PATH"); 
    
            try{
                if(!file.exists()){
                    // create propeties file add properties
                }
            } catch (IOException e) {
             //HANDLE EXCEPTION
            }
            SpringApplication.run(SpringDocBotApplication.class, args);
        }
    }