温馨提示×

如何在Spring Boot中将Cache-Control标头添加到静态资源中

小云
119
2023-09-27 08:44:28
栏目: 编程语言

要在Spring Boot中将Cache-Control标头添加到静态资源中,可以使用WebMvcConfigurer接口的addResourceHandlers方法来配置静态资源处理器。

首先,创建一个类实现WebMvcConfigurer接口,并重写addResourceHandlers方法。在该方法中,使用addResourceHandler方法指定静态资源的URL路径,并使用addResourceLocations方法指定静态资源的文件路径。然后,使用setCacheControl方法为静态资源添加Cache-Control标头。

下面是一个示例代码:

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/")
.setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
}
}

在上述示例中,静态资源的URL路径为"/static/**“,静态资源的文件路径为"classpath:/static/”。使用setCacheControl方法将Cache-Control标头添加到静态资源中,并设置缓存的最大期限为365天。

接下来,将该类注解为@Configuration,以便Spring Boot能够自动识别并加载该配置。

这样,当访问静态资源时,就会在响应头中添加Cache-Control标头。

0