首页 文章

从文件系统提供静态资源| Spring Boot Web

提问于
浏览
15

使用Spring Boot Web应用程序我尝试从项目外部的文件系统文件夹中提供静态资源 .

文件夹结构如下: -

src
             main
                 java
                 resources
             test
                 java
                 resources
          pom.xml
          ext-resources   (I want to keep my static resources here)
                 test.js

spring 配置: -

@SpringBootApplication
public class DemoStaticresourceApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(DemoStaticresourceApplication.class, args);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**").addResourceLocations("file:///./ext-resources/")
                .setCachePeriod(0);
    }
}

在浏览器中点击“http://localhost:9999/test/test.js”会返回404 .

我应该如何配置ResourceHandlerRegistry来提供上述'ext-resources'文件夹中的静态资源?

我应该能够为dev / prod环境打开/关闭缓存 .

谢谢

UPDATE 1

给绝对文件路径有效: -

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**")
                .addResourceLocations(
                        "file:///C:/Sambhav/Installations/workspace/demo-staticresource/ext-resources/")
                .setCachePeriod(0);
}

我怎样才能提供相对位置?绝对路径将使我的生活在构建和部署过程中变得艰难 .

4 回答

  • 23

    file:/// 是指向文件系统根目录的绝对URL,因此, file:///./ext-resources/ 表示Spring Boot正在根目录中名为 ext-resources 的目录中查找资源 .

    更新您的配置以使用类似 file:ext-resources/ 的URL作为URL .

  • 3

    Spring Boot配置管理允许多个策略(see Boot reference documentation) .

    虽然在这里使用静态的完整路径,但我建议您不要使用该策略,因为团队中的每个开发人员都不会共享相同的工作区布局 .

    您可以使用在that example project中选择的一些策略,并使此路径成为配置属性 .

    一旦这是一个属性,让我们说 resources.projectroot ,设置这个的几种方法:

    • 每个开发人员在她的 application.ymlapplication.properties 文件中手动设置此值

    • 在运行项目时使用env变量,如 RESOURCES_PROJECTROOT=/home/user/demo/ ./gradlew bootRun (此处为gradle unix)或 set RESOURCES_PROJECTROOT=%cd% mvn spring-boot:run (此处为maven windows)

    您可能会通过查看构建工具,您选择的操作系统以及Boot提供的所有配置策略,找到满足您需求的许多其他解决方案 .

  • 1

    这是我在WebConfig类中在addResourceHandlers方法中所做的:

    boolean devMode = this.env.acceptsProfiles("development");
    String location;
    if (devMode) {
        String currentPath = new File(".").getAbsolutePath();
        location = "file:///" + currentPath + "/client/src/";
    } else {
        location = "classpath:static/";
    }
    
  • 1

    Spring Boot Maven插件可以为类路径添加额外的目录 . 在你的情况下,你可以把它包括在你的pom中 .

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>${spring.boot.version}</version>
        <configuration>
            <folders>
                <folder>${project.build.directory}/../ext-resources</folder>
            </folders>
    
            ...
        </configuration>
    </plugin>
    

    因此,您不需要在类中包含任何硬代码 . 只需启动您的webapp即可

    mvn spring-boot:run
    

相关问题