Spring boot app打包成jar后不提供静态资源 [英] Spring boot app does not serve static resources after packaging into jar

查看:79
本文介绍了Spring boot app打包成jar后不提供静态资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过 ide 或命令行启动时运行良好的应用程序:mvn spring-boot:run.但是当我把它打包成 jar 时,我无法访问静态资源(404 not found).我不想将静态文件存储在资源文件中,因此每次需要更改静态文件时都不必重新加载服务器.所以我在我的 pom.xml 中使用了这个插件:

I have a application that work perfectly fine when started via ide or command line: mvn spring-boot:run. But when i package it into jar, I cannot access static resources(404 not found). I did not want to store static files in resource fouler so i don`t have to reload the server each time i need to change static file. So i used this plugin in my pom.xml:

              <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/classes/static</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/webapp</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

我可以看到文件被复制到两个静态"目录中.这是我对资源处理程序的配置:

I can see that files are being copied in two the directory "static". This is my configuration of resource handler:

    @Configuration
    @EnableWebMvc
    public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/");
    }

控制器 RequestMappings 工作正常,问题仅在于静态资源.

Controllers RequestMappings are working fine, problems are only with the static resources.

推荐答案

你应该提供多个资源位置来解决:

You should supply multiple resource locations for resolving:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**").addResourceLocations("/", "classpath:/static/");
}

这篇关于Spring boot app打包成jar后不提供静态资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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