为什么当我 运行 项目时它无法从属性文件中读取属性?

why when i run project it can not read properties from properties file?

我在基于 mule 的项目中有 service.properties 和 service-properties.xml。我如何定义 service.properties 应该在 service-properties.xml 之前加载? 因为我在service-properties.xml中使用了service.properties的属性。 因为我在 service-properties.xml 文件中有这段代码:

    <context:property-placeholder
        location="classpath:mule/service.properties"
        properties-ref="propertiesHolder" />
    <context:annotation-config />   
   <spring:bean id="propertiesHolder"
        class="MyClass">
        <spring:property name="dataSource" ref="dataSource" />
    </spring:bean>
    <spring:bean id="dataSource"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

       <spring:property name="driverClassName value="${db.driverClassName}" />
        <spring:property name="url" value="${db.url}" />
        <spring:property name="username" value="${db.username}" />
        <spring:property name="password" value="${db.password}" />
    </spring:bean>

我的项目构建成功,但是当我 运行 项目时,它无法从 service.properties 解析 db.driverClassName、db.url、...和 ​​db.password但我在 service.properties 文件中有它们。

如果您使用 context:property-placeholder 在同一上下文中加载属性文件和配置文件,那么 Mule/Spring 会为您处理,应该没有问题:

https://docs.mulesoft.com/mule-user-guide/v/3.7/configuring-properties

我认为您的应用程序未能解析这些属性,因为您在 property-placeholder 中包括 一个 location 属性和一个 properties-ref 属性] 配置。 properties-ref 属性旨在替换 location 属性,以便提供 java.util.Properties 对象的属性值。

试试这个:

<context:property-placeholder location="classpath:mule/conversion/service.properties" />

然后您可以简单地引用 dataSource bean 中的属性。

没有显式引用连接使用属性 (dataSource) 的 bean 和加载属性的 bean 的原因是 <context:property-placeholder /> 元素定义了一个 BeanFactoryPostProcessor。这是一种特殊的 bean,可以在实例化之前修改其他 bean 的定义。它使用 ${propertyName} 语法搜索 bean 属性并在 Spring 尝试实例化它们之前替换它们。

更新:如何从数据库加载属性,由属性配置

如果您的目标是从数据库加载配置属性,并使用另一个属性文件配置与该数据库的连接,请查看 this Whosebug question

我可以通过此配置从文件和数据库中读取属性:

   <spring:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <spring:property name="locations">
            <spring:value>classpath:mule/service.properties</spring:value>
        </spring:property>
        <spring:property name="properties">
            <spring:value>propertiesFromDataSource</spring:value>
        </spring:property>
    </spring:bean>