从SpringBoot源码看资源映射原理,javaweb开发面试题

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip1024b (备注Java)
img

正文

上边的这种配置方式是属于XML配置的方式,SpringMVC的配置方式除了XML配置,也是可以通过java代码配置的,只需要我们自己定义一个类,来继WebMvcConfigurationSupport这个类即可,我们看一下WebMvcConfigurationSupport的源码部分:

/**

  • Override this method to add resource handlers for serving static resources.

  • @see ResourceHandlerRegistry

*/

protected void addResourceHandlers(ResourceHandlerRegistry registry) {

}

上边的注释写的很清楚,重写这个方法来增加一个静态资源的映射。那么具体怎么写呢?

我们再按照注释看一下ResourceHandlerRegistry的源码,重点看一下对这个类的注释,如下。

/*

To create a resource handler, use {@link #addResourceHandler(String…)} providing the URL path patterns

/ * for which the handler should be invoked to serve static resources (e.g. {@code “/resources/**”}).

大概意思就是为了创建资源的处理器,要调用addResourceHandler方法来提供url的表达式,这个方法是为了服务静态资源的(ps:英语水平也一般,了解大意即可)

然后我们去看addResourceHandler方法:

/**

  • Add a resource handler for serving static resources based on the specified URL path patterns.

  • The handler will be invoked for every incoming request that matches to one of the specified

  • path patterns.

  • Patterns like {@code "/static/**"} or {@code "/css/{filename:\\w+\\.css}"} are allowed.

  • See {@link org.springframework.util.AntPathMatcher} for more details on the syntax.

  • @return a {@link ResourceHandlerRegistration} to use to further configure the

  • registered resource handler

*/

public ResourceHandlerRegistration addResourceHandler(String… pathPatterns) {

ResourceHandlerRegistration registration = new ResourceHandlerRegistration(pathPatterns);

this.registrations.add(registration);

return registration;

}

我们看到这个方法执行后返回了一个新的类ResourceHandlerRegistration

那我们再来看一下这个类中的核心方法

/**

  • 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.

  • 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.

  • 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) {

this.locationValues.addAll(Arrays.asList(resourceLocations));

return this;

}

上边注释的大意就是增加一个或者多个静态资源路径,并举了一些例子。源码我们就看到这里。

所以我们可以像这样实现资源的映射:

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**

  • @author liumeng

  • @Date: 2020/9/25 09:20

  • @Description:

*/

@Configuration

public class SpringMvcConfig extends WebMvcConfigurationSupport {

@Override

protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(“/**”).addResourceLocations(“/”);

}

}

关于SpringMVC中的资源映射部分就介绍到这,那么我们继续来看SpringBoot的资源映射吧。

SpringBoot的资源映射

===================

其实SpringBoot的资源映射也是一脉相承的,当我们初始化一个SpringBoot项目后,静态资源会默认存在resource/static目录中,那么SpringBoot的底层是怎么实现的呢,接下来我们就去源码里探索一下。

SpringBoot的源码在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();

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)); } }

这里面我们重点看下边这部分

String staticPathPattern = this.mvcProperties.getStaticPathPattern();

if (!registry.hasMappingForPattern(staticPathPattern)) {

customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern) .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))

.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); }

我们看一下getStaticPathPattern()方法的实现,发现获得的就是

/**

  • Path pattern used for static resources.

*/

private String staticPathPattern = “/**”;

这个属性的值,默认是/**。

然后我们再看this.resourceProperties.getStaticLocations()方法,发现获得的是

private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

而CLASSPATH_RESOURCE_LOCATIONS是一个常量,值如下:

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { “classpath:/META-INF/resources/”,

“classpath:/resources/”, “classpath:/static/”, “classpath:/public/” };

结语

小编也是很有感触,如果一直都是在中小公司,没有接触过大型的互联网架构设计的话,只靠自己看书去提升可能一辈子都很难达到高级架构师的技术和认知高度。向厉害的人去学习是最有效减少时间摸索、精力浪费的方式。

我们选择的这个行业就一直要持续的学习,又很吃青春饭。

虽然大家可能经常见到说程序员年薪几十万,但这样的人毕竟不是大部份,要么是有名校光环,要么是在阿里华为这样的大企业。年龄一大,更有可能被裁。

送给每一位想学习Java小伙伴,用来提升自己。

在这里插入图片描述

本文到这里就结束了,喜欢的朋友可以帮忙点赞和评论一下,感谢支持!

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

自己。

[外链图片转存中…(img-gH5bfHYp-1713679258508)]

本文到这里就结束了,喜欢的朋友可以帮忙点赞和评论一下,感谢支持!

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
[外链图片转存中…(img-n4iDxzJ4-1713679258508)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 13
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值