一、前言

通过查看源代码的方式来了解springboot引用静态资源的机制。

二、方法

  • webjars

  1、源码

  打开WebMvcAutoConfiguration这个文件,找到addResourceHandlers方法

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
        return;
    }
    addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
    addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
        registration.addResourceLocations(this.resourceProperties.getStaticLocations());
        if (this.servletContext != null) {
            ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
            registration.addResourceLocations(resource);
        }
    });
}

  2、实现步骤

  进入webjars官网https://www.webjars.org/ ,找到你要引入的项目,选择maven形式复制代码

  

  引入到maven文件中

  

  在External Libraries中找到引入的项目

  

  3、访问方式

  localhost:8080/webjars/ace/01.08.2014/editor.html,其中/webjars/对应实际目录中的/META-INF/resources/webjars/

  • resourcse

  1、源码

  还是第一个方法里的代码,点击this.resourceProperties.getStaticLocations(),进去之后会发现源码里定义了{ "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" }这几个静态目录

  2、实现步骤

  自行创建相关目录,这些目录如果存在相同名称的文件,优先级为resources>static>public。所以public下面一般可以放公共资源;static可以放静态资源,如图片等;resources就放上传的文件。

  

  3、访问方式

  localhost:8080/demo.js,程序就会自动从这三个文件夹中去找,优先级如上。