【问题标题】:How to create a directory on statup in spring boot projectspring boot项目启动时如何创建目录
【发布时间】:2019-10-04 20:01:36
【问题描述】:

我正在创建一个目录,以便在启动时将所有上传的文件存储在我的 Spring Boot 应用程序中。

该目录的路径存储在 application.properties 文件中。 我正在尝试读取此路径并在 startupof 项目上创建一个目录。在启动时创建目录时我无法获取路径。

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

}

【问题讨论】:

  • this answer 可能会有所帮助。
  • 我最近在我的 Spring Boot 应用程序中做了同样的事情,如果你没有找到合适的解决方案,请告诉我,我可以告诉你我是怎么做的。
  • 将您的存储属性设为组件并注册一个事件 ApplicationReady 并在此处编写您的业务逻辑以创建文件夹

标签: java spring-boot web jakarta-ee file-handling


【解决方案1】:
  • 第 1 步:将 StorageProperties 设为组件
  • 第 2 步:在 StartUpComponent 中自动装配该组件
  • 第三步:创建文件夹
@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
  }
}

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 2019-08-25
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2020-01-16
    • 2019-12-03
    • 2020-04-01
    • 2020-08-04
    相关资源
    最近更新 更多