Spring Boot之如何配置静态资源的地址与访问路径

        使用前端框架例如React、Vue等开发完成的项目,如何集成到后端项目后一起部署到服务器上呢?这就涉及到了在后端项目中如何配置静态资源的地址与访问路径,下面将为大家详细介绍。

        React项目打包完成的结构,如下:

        

        Spring Boot项目的结构,如下:

        

Spring Boot默认的静态资源文件配置:

 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {

"classpath:/META-INF/resources/", "classpath:/resources/",

"classpath:/static/", "classpath:/public/" };        

        默认的静态资源文件夹:为static/public,遵循spring boot默认规则,基本可以满足我们大部分的需求了。

扫描二维码关注公众号,回复: 2287585 查看本文章

如果我们需要自定义,这里提供两种方法:

1:application.properties方法

这里的static可以换成你对应的文件夹名字


如:build


对应路径如下:


访问路径:

http://localhost:8080/build/index.html

2:重写 WebMvcConfigurerAdapter配置

package com.envision.mobile.service.utils; 

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class ReactWebAppConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }

}

上面具体的个性配置,也一样,修改对应的ResourceHanders与ResourceLocations即可。

猜你喜欢

转载自blog.csdn.net/tiangongkaiwu152368/article/details/80844647