LoginSignup
4
0

More than 5 years have passed since last update.

ハマりメモ:spring-boot-starter-parentを継承した時のmaven-resources-pluginの挙動

Last updated at Posted at 2016-11-25

TL;DR

spring-boot-starter-parent を継承してpomを作成しているプロジェクトで maven-resources-plugin のリソースフィルタリング機能を使う場合、フィルタリングする箇所は ${} ではなく @@ で囲まなければならない。
(Spring Bootのマニュアルにも載っている)

要件

Spring Bootを使ったWebアプリでCache bustingをしたい。

行おうとした実装

SpringにはVersionResourceResolverを使ってお手軽にフィンガープリントをつけられる機能があるが、今回はファイル名が変わるとまずい事情があるのでそれは使えなかった。
そこで、
1.Mavenビルド時に${maven.build.timestamp}で日付を取得して、プロパティファイルにセット
2.それをHTML側からthymeleafで取得し、クエリ文字列としてセット
という手順で実装することにした。

ハマった点

以下のようにしたところ、プロパティファイルにビルド日時が設定されてくれなかった。
設定は間違っていないはず・・・

pom.xml
...

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.5.RELEASE</version>
    <relativePath/>
</parent>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <project.build.timestamp>${maven.build.timestamp}</project.build.timestamp>
    <maven.build.timestamp.format>yyyyMMdd</maven.build.timestamp.format>
</properties>

...

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
                <resources>
                    <resource>
                        <directory>src/main/resources</directory>
                        <filtering>true</filtering>
                    </resource>
                </resources>
            </configuration>
        </plugin>
    </plugins>
</build>

...

application.properties
# Cache busting
app.build.timestamp=${project.build.timestamp}
layout.html
<link rel="stylesheet" type="text/css" th:href="'/css/common.css?v=' + @{__${@environment.getProperty('app.build.timestamp')}__}" />
<script type="text/javascript" th:src="'/js/commons/common.js?v=' + @{__${@environment.getProperty('app.build.timestamp')}__}"></script>

原因

頑張ってググったところ、マニュアルに答えが書いてあった模様。
http://stackoverflow.com/questions/35417086/maven-resource-filtering-with-spring-boot-could-not-resolve-placeholder
http://docs.spring.io/spring-boot/docs/1.3.0.RELEASE/reference/html/howto-properties-and-configuration.html#howto-use-short-command-line-arguments

要約すると、spring-boot-starter-parent を継承してpomを作成している場合、maven-resources-plugin がフィルタリングに用いるトークンは、${} から @@ に変更される、との事。

つまり、こうするのが正しかった。

application.properties
# Cache busting
app.build.timestamp=@project.build.timestamp@
4
0
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
4
0