如何在Spring Boot中將Cache-Control標(biāo)頭添加到靜態(tài)資源中

小云
164
2023-09-27 08:44:28
欄目: 編程語言

要在Spring Boot中將Cache-Control標(biāo)頭添加到靜態(tài)資源中,可以使用WebMvcConfigurer接口的addResourceHandlers方法來配置靜態(tài)資源處理器。

首先,創(chuàng)建一個(gè)類實(shí)現(xiàn)WebMvcConfigurer接口,并重寫addResourceHandlers方法。在該方法中,使用addResourceHandler方法指定靜態(tài)資源的URL路徑,并使用addResourceLocations方法指定靜態(tài)資源的文件路徑。然后,使用setCacheControl方法為靜態(tài)資源添加Cache-Control標(biāo)頭。

下面是一個(gè)示例代碼:

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

在上述示例中,靜態(tài)資源的URL路徑為"/static/**“,靜態(tài)資源的文件路徑為"classpath:/static/”。使用setCacheControl方法將Cache-Control標(biāo)頭添加到靜態(tài)資源中,并設(shè)置緩存的最大期限為365天。

接下來,將該類注解為@Configuration,以便Spring Boot能夠自動(dòng)識(shí)別并加載該配置。

這樣,當(dāng)訪問靜態(tài)資源時(shí),就會(huì)在響應(yīng)頭中添加Cache-Control標(biāo)頭。

0