Spring Boot之application.properites的failed to convert java.lang.String to java.lang.Integer問題解決

環境描述

Spring Boot 2.0.4.RELEASE

問題描述

新創建了一個Spring Boot的Web應用,在pom.xml中的profile中配置了web server的端口,並在application.properties中配置了對應的port字段映射。
但是,在啓動過程中,卻出現瞭如下錯誤信息:


***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'server.port' to java.lang.Integer:

    Property: server.port
    Value: @app.server.port@
    Origin: class path resource [application.properties]:4:13
    Reason: failed to convert java.lang.String to java.lang.Integer

Action:

Update your application's configuration

pom.xml中對應的配置如下:

     <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>

            <properties>
                <app.name>robotcode</app.name>
                <app.log.level>debug</app.log.level>
                <app.server.port>1090</app.server.port>
            </properties>
        </profile>

應用中的application.properties的配置如下:

spring.application.name=Robot Code Application
server.port=@app.server.port@

問題分析

針對問題的錯誤信息,嘗試進行猜測:
1. 端口的字段名稱配置錯誤, 導致真實的端口沒有出現。
2. 端口的不能這麼配置,方式問題
3. app.server.port這個字段值需要自行類型轉換嗎?

猜測1, 經過檢查,問題不存在。 猜測2: 應該沒有問題。 猜測3: Spring Boot如果配置一個端口都需要自行轉換,那這個框架設計的就臺lower了。

那問題是不是字段未被替換,或者替換的值不對呢?
大概率應該是並未被替換,所以,在轉換過程中,出現類型錯誤信息。

mvn package

自行打包一次,進行檢查,果然如此。

問題解決

在pom.xml中配置相應的過濾替換機制:

    <plugins>
        ............
         <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin> -->
        </plugins>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

總結

重新執行一下,問題被完美解決。哈哈,一個很有意思的問題,能夠加深大家對於PropertyPlaceLoader等相關方法的理解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章