How to create a directory on statup in spring boot project

拟墨画扇 提交于 2019-12-11 12:43:07

问题


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

}

回答1:


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


来源:https://stackoverflow.com/questions/56187233/how-to-create-a-directory-on-statup-in-spring-boot-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!