Spring配置文件无法读取properties

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring配置文件无法读取properties

琴弦第七   2022-05-28 我要评论

Spring配置文件无法读取properties

在Spring项目的配置文件中引用properties属性文件中的属性,运行时无法识别properties属性文件中的属性引用,但properties属性文件和属性明明已经存在

例如:

要在Spring中使用外部properties属性文件,需要在Spring配置文件中添加bean后处理器PropertyPlaceholderConfigurer,并指明外部properties属性文件的路径:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations" value="properties路径"/>
</bean>

如果有多个properties属性文件,可以使用下面方式:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>properties路径</value>
            <value>properties路径</value>
            ...
        </list>
    </property>
</bean>

@Value读取properties类型错误

Invalid boolean value [${spring.datasource.testWhileIdle}]

在开发过程中,遇到一个比较无语的问题:重新拉一份代码搭框架,在启动的时候读取properties配置文件报类型转换错误,因为代码是一样的,所以排除代码的问题,在百度谷歌搜索了一遍没有找到能够解决的办法

先贴上报错信息:

Unsatisfied dependency expressed through field 'testWhileIdle'; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [${spring.datasource.testWhileIdle}]

我们可以看到,报错信息给我们的提示是,String转Boolean类型错误。

这里使用了spring的@Value注解,我在配置文件中填的是 true。

后来我对读到的参数进行强转类型,依旧报错。可以确定取到的值是不正确的

经过测试,读取值,发现读取到的值为 spring.datasource.testWhileIdle 而不是 true (spring在读取配置文件时,如果不能读取到,@Value取到的值就是括号里面的值,有点坑。)

我们可以断定未加载properties成功。

知道了读取不到的真正原因之后,其实再去搜索问题就比较简单了。

eclipse解决方案

由于eclipse配置源代码excludes过滤掉了application.properties或application.yml造成的,具体位置在: Project Properties --> Java Build Path --> Source(tab) --> Source folders on build path: [Exclusion section]

idea解决方案

目前在idea里的配置我还不太清楚,我用的是idea,最后通过pom.xml解决问题

引入properties,最终解决。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们