springboot 访问静态资源设置

今天一个人问我为什么项目下的图片不能访问,帮他解决问题后我决定记录下来,springboot 的程序的静态资源访问需要重写addResourceHandlers方法,直接上代码:

import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class WebAppConfig implements WebMvcConfigurer  {
	
	//存放静态资源的地址
	private static final String ROOT = "D:/test/systemfile";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	//替换成修改后url访问的路径
        registry.addResourceHandler("/systemfile/**").addResourceLocations("file:"+ROOT+"/");
        registry.addResourceHandler("/ueditor/**").addResourceLocations("file:"+ROOT+"/ueditor/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/")
        					.addResourceLocations("classpath:/resources/")
					        .addResourceLocations("classpath:/static/")
					        .addResourceLocations("classpath:/public/");
    }
    
    @Override
    public void addViewControllers( ViewControllerRegistry registry ) {
        registry.addViewController( "/" ).setViewName( "forward:/index.html" );
        registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
    } 
}

然后记得在application中加上 

@ServletComponentScan 注解

简单的实现springboot静态资源访问。

猜你喜欢

转载自blog.csdn.net/atmknight/article/details/81536627