Spring Boot 默认配置
在一个Web项目中往往需要处理一些静态资源的请求,比如css,js,image文件的等。Spring Boot提供了一种很简单的方式,即使用默认配置。
在application.properties的配置清单中可以看到这些属性:
配置项 | 默认值 | 含义 |
---|---|---|
spring.resources.add-mappings |
true | Whether to enable default resource handling. |
spring.resources.static-locations |
classpath:/META-INF/resources/ , classpath:/resources/ , classpath:/static/ , classpath:/public/ |
Locations of static resources. Defaults to classpath:[/META-INF/resources/, /resources/, /static/, /public/]. |
也就是说,默认是启用了静态资源映射的,并且,当文件在classpath:/META-INF/resources/
, classpath:/resources/
, classpath:/static/
, classpath:/public/
这四个目录下的话可以直接返回。
但是,如果开发者不希望将这四个目录定为静态资源目录,而是只指向某一个(既可以是上面四个目录其中之一,也可以是一个自定义的目录),那么可以修改配置文件中的上述配置项,或者通过Java代码的方式进行配置。
使用Java代码配置
首先在Spring的ComponentScan可以扫描到的目录创建一个WebConfig类,然后重写addResourceHandlers方法:
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/","file:///E:/");
}
}
其中,addResourceLocations可以支持添加多个目录,并且这些目录类型涵盖了classpath/file/http:
/**
* Add one or more resource locations from which to serve static content.
* Each location must point to a valid directory. Multiple locations may
* be specified as a comma-separated list, and the locations will be checked
* for a given resource in the order specified.
* <p>For example, {{@code "/"}, {@code "classpath:/META-INF/public-web-resources/"}}
* allows resources to be served both from the web application root and
* from any JAR on the classpath that contains a
* {@code /META-INF/public-web-resources/} directory, with resources in the
* web application root taking precedence.
* <p>For {@link org.springframework.core.io.UrlResource URL-based resources}
* (e.g. files, HTTP URLs, etc) this method supports a special prefix to
* indicate the charset associated with the URL so that relative paths
* appended to it can be encoded correctly, e.g.
* {@code [charset=Windows-31J]https://example.org/path}.
* @return the same {@link ResourceHandlerRegistration} instance, for
* chained method invocation
*/
public ResourceHandlerRegistration addResourceLocations(String... resourceLocations);
上面的配置代码会覆盖原来的默认设置,导致默认指定的四个目录失效。
总结
- Spring Boot默认是开启了静态资源映射的,并且会扫描四个目录
- 使用Java配置ResourceHandler会覆盖默认设置
- 使用Java配置的代码(使用Configration注解的类)必须能被Spring扫描到并加载
addResourceLocations
中的地址中可以使用classpath:/
。在Spring中src/main/resources目录下的文件会直接放到classpath中。当编译完成时这个目录下的所有内容应该会输出到target/classes
中,因此classpath:/
等同于target/classes/
。- addResourceLocations可以添加多个目录,支持的类型有classpath,http,file等。在windows中file目录的格式参考这里。