如果我使用 JVM 变量设置位置,如何将 *.properties 中的参数设置为 SPRING appContext.xml?

How to set parameter from *.properties into SPRING appContext.xml if i set location with JVM variable?

我有一个 VM 参数 -Dapp.conf=/path/to/config.properties,我的 Spring 4.2.5 应用程序有一个 appContext.xml。 此 config.properties 包含类似 database.username=username

的属性

在 XML 配置中我有这个 bean <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value= "${database.driver}"/> <property name="url" value="${database.url}"/> <property name="username" value="${database.username}"/> <property name="password" value="${database.password}"/> </bean>

我正在尝试使用此读取我的配置文件:

 `<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
    <property name="location" value="file:///#{systemEnvironment['app.conf']}"/>
</bean>`

但是我插入的参数value= "${database.driver}没有从文件中读取。

如何将属性文件中的参数插入数据源?

在这种情况下,它只是插入 ${database.driver} 并且我有例外,该参数无效。

在 Spring BOOT 中我做了这个并且成功了:

        Properties properties = new Properties();
    try (Reader reader =
                 new FileReader(
                         System.getProperty("app.conf")
                       //this contains path:"D://config.properties"
                 )) {
        properties.load(reader);
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
    for (String propertyName: properties.stringPropertyNames()) {
        System.setProperty(propertyName, properties.getProperty(propertyName));
    }

此代码将我的属性加载为 VM 参数,我可以使用 Spring 注释访问它们 @Value("#{property.name}")

我不知道为什么,但是 System.setProperties(properties); 没用。