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等相关方法的理解。

猜你喜欢

转载自blog.csdn.net/blueheart20/article/details/81480864
今日推荐