About springboot2. * Version can not load static resources

Foreword

In the process of learning springboot, it was found not reference static resources. I am using springboot2.2.1 version.

Traceable source, and finally resolved. And record Solutions.

Default load path

First of all you have to know what the load was springboot default resource path yes.

First we look at WebMvcAutoConfiguration this class. Inside there is a method called addResourceHandlers ()

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
        ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
                @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
                return;
            }
            Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
            CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
            
            //所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源
            if (!registry.hasMappingForPattern("/webjars/**")) {
                customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
                        .addResourceLocations("classpath:/META-INF/resources/webjars/")
                        .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
            }
            
            //静态资源文件夹映射
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
            if (!registry.hasMappingForPattern(staticPathPattern)) {
                customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
                        .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
                        .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
            }
        }
}

First, we will springboot classpath: file mapping in the / META-INF / resources / webjars / path / webjars / **

And then determine if a static resource folder mapping, we first determine whether to use the "/ **" do mapping

If not, the "/ *" to access the current project of any resources, you go (following static resource files folder) to find Mapping

"classpath:/META‐INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径

What does that mean? As an example, that if we default, we call http: // localhost: 8080 / a.json

Springboot will find a.json this file from the above get these paths.

problem lies in

As was also the source guess so, why my code, but can not directly access a static resource mapping done it?

We take a closer look WebMvcAutoConfiguration this class. At its head with a comment that:

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

FML, instantly understood why. I have a configuration file:

@Configuration
public class MyMVCConfig extends WebMvcConfigurationSupport{
    ...
}

WebMvcConfigurationSupport inherited this class, so that the failure of the automatic assembly springboot. Because the effect is obtained @ConditionalOnMissingBean This annotation, when the container does not exist in this class, the following codes have to have effect.

Why is this design?

Because sometimes we have to project springboot do not want to give us automatic assembly. Hope fully configured by our own own to master.

To achieve this effect, springboot provides us with a more concise way too.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

@EnableWebMvc annotations import DelegatingWebMvcConfiguration.clss
and DelegatingWebMvcConfiguration also inherited the WebMvcConfigurationSupport

public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

So when we get together @EnableWebMvc will have the same effect and concise.

Custom configuration resource mapping

springboot course, we also support personalization have to specify the mapping path, I summed up as follows several ways:

Configuration class

@Configuration
public class MyMVCConfig extends WebMvcConfigurationSupport{

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

The above means: to get all the files in / static all mapped to / static / **

Configuration Item

Add the following entry in the configuration file application.properties

spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
  classpath:/static/,classpath:/public/

spring.mvc.static-path-pattern = / **: indicates that all access is through the static resource path;

spring.resources.static-locations: here configure a static resource path.

Guess you like

Origin www.cnblogs.com/zhxiansheng/p/11931436.html