如何在Spring Boot项目中的statup上创建目录 [英] How to create a directory on statup in spring boot project

查看:91
本文介绍了如何在Spring Boot项目中的statup上创建目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个目录,用于在启动时将所有上载的文件存储在我的spring boot应用程序中.

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

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

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.

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步:使StorageProperties成为组件
  • 第2步:自动将该组件连接到StartUpComponent中
  • 第3步:创建您的文件夹
  • @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
      }
    }
    

    这篇关于如何在Spring Boot项目中的statup上创建目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆