LoginSignup
21
16

More than 5 years have passed since last update.

Spring Bootで静的リソースのブラウザキャッシュ対応

Last updated at Posted at 2016-02-19

備忘のためメモ。
要は、ファイル内容に応じたハッシュ値をリソースのファイル名に埋め込んで、ブラウザキャッシュを制御したいのです。

イメージ
<script src="/js/dist/bundle-58c07a622ea3c101af0d90c6e5f2547f.js"></script>

環境

Spring Boot 1.3.0.RELEASE

設定

application.ymlに以下を追加するだけで実現可能。
※ pathsは対象にしたいファイルによって要調整。

application.yml
spring:
  resources:
    chain:
      strategy:
        content:
          enabled: true
          paths: /**

ハッシュ値を生成しているのは

org.springframework.web.servlet.resource.ContentVersionStrategy#getResourceVersion

の処理。
コード見ると分かりますが、実際のリソースのStreamからハッシュ値を生成しているので、リソースに改修が入ればハッシュ値も変わります。

ハッシュ値とリソースを紐付けるのは

org.springframework.web.servlet.resource.VersionResourceResolver

あたりの処理。

thymeleaf上でリンクURL式で指定しておけば

thymeleaf
<script th:src="@{/js/dist/bundle.js}"></script>

実HTMLではハッシュ値付きのパスで出力されます。

HTML(イメージ)
<script src="/js/dist/bundle-58c07a622ea3c101af0d90c6e5f2547f.js"></script>
21
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
16