spring boot ---静态资源

以你之姓@ 2022-03-11 01:16 406阅读 0赞

在 spring mvc 中,对于静态资源也需要手动的配置,但是在spring boot 中是不需要手动配置的,提供了自动化配置,可以简化静态资源的过滤配置

spring boot 中 对于 spring mvc 的自动化配置都在WebMvcAutoConfiguration 类中,在webMvcAutoConfiguration 类中有一个静态内部类WebMvcConfigurationAdapter ,在该类中有一个方法, addResourceHandlers,在该方法中有一句

  1. this.resourceProperties.getStaticLocations() ,获取的是
  2. public String[] getStaticLocations() {
  3. return this.staticLocations;
  4. }

而该返回的数据是

  1. private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
  2. "classpath:/META-INF/resources/", "classpath:/resources/",
  3. "classpath:/static/", "classpath:/public/" };
  4. /**
  5. * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
  6. * /resources/, /static/, /public/].
  7. */
  8. private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

可以看到在spring mvc 中设置了路径

但是在 getResourceLocations 该方法中,获取了

  1. static String[] getResourceLocations(String[] staticLocations) {
  2. String[] locations = new String[staticLocations.length
  3. + SERVLET_LOCATIONS.length];
  4. System.arraycopy(staticLocations, 0, locations, 0, staticLocations.length);
  5. System.arraycopy(SERVLET_LOCATIONS, 0, locations, staticLocations.length,
  6. SERVLET_LOCATIONS.length);
  7. return locations;
  8. }

中的 SERVLET_LOCATIONS 静态变量

  1. private static final String[] SERVLET_LOCATIONS = { "/" };

表示 spring boot 会过滤掉所有的 静态资源

在使用 idea 创建 spring boot 项目的时候,会默认创建出 static 目录,可用于存放静态资源

在使用的时候,也可以自定义存放的路径

  1. spring.mvc.static-path-pattern=/static/**
  2. spring.resources.static-locations= classpath:/static/

也可以使用 Bean 来创建 文件存放的路径,, 在使用bean 的时候,需要实现 WebMvcConfigurer类

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

发表评论

表情:
评论列表 (有 0 条评论,406人围观)

还没有评论,来说两句吧...

相关阅读