您的位置 首页 java

springboot 定制静态资源路径

1、springboot 1.x中,使用WebMvcConfigurerAdapter

 import org.springframework.context. annotation .Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandler registry ;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfig  extends  WebMvcConfigurerAdapter {
   @Value("${spring.resources. static -locations}")
     private  String staticLocations;
  
    public  void  addResourceHandlers(ResourceHandlerRegistry registry) {
      				registry.addResourceHandler("/**").addResourceLocations(staticLocations);
    }
}  

配置文件中指定spring.resources.static-locations键值

 spring.resources.static-locations=file:d:/project/pay/dist/  

2、springboot2.x版本

在springboot 2.x版本中WebMvcConfigurerAdapter类已被标注为@Deprecated,不推荐使用,推荐使用WebMvcAutoConfiguration类。

 @Deprecated
public  abstract  class WebMvcConfigurerAdapter implements WebMvcConfigurer {
}  
 
@Configuration( proxyBeanMethods = false)
@ConditionalOnWebApplication( type = Type.SERVLET)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
  
}  

方式一:使用配置文件

直接在application.properties配置文件中添加下面配置项,表示将本地路径下的文件夹全部文件映射到该项目中根目录中。

 spring.resources.static-locations=file:d:/project/pay/dist/
spring.mvc.static-path-pattern=/**  

方式二:使用 Java 代码

自定义配置类,实现接口WebMvcConfigurer的方法addResourceHandlers()即可

 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class StaticWebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("file:d:/project/pay/dist");
    }
}  

文章来源:智云一二三科技

文章标题:springboot 定制静态资源路径

文章地址:https://www.zhihuclub.com/190425.shtml

关于作者: 智云科技

热门文章

网站地图