How to create a directory on statup in spring boot project

omkar :

I am making a directory to store all uploaded files in my spring boot app on startup.

The path of this directory is stored in application.properties file. I am trying to read this path and create a directory on startupof project. I am not able to get the path while creating a directory on startup.

application.properties

upload.path = "/src/main/resources"

StorageProperties.java

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "upload")
public class StorageProperties {

    private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

}
Dirk Deyne :
  • Step1: make you StorageProperties a Component
  • Step2: autowire that component in your StartUpComponent
  • Step3: create your folder
@Component
@ConfigurationProperties(prefix = "upload")
public class StorageProperties {

  private String path;

  // getters and setters
}
@Component
public class StartupComponent implements CommandLineRunner {
   private final StorageProperties storageProps;

   public StartupComponent (StorageProperties storageProps){
     this.storageProps = storageProps;
   }

  @Override
  public void run(String... args) throws Exception {
     String path = storageProps.getPath();
     // do your stuff here
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156967&siteId=1