将文件中的值读入 applicationContext.xml 文件

Reading value from file into applicationContext.xml file

我有一个基于 spring 的 Web 应用程序,在我的应用程序上下文 xml 文件中,我定义了一个具有连接到数据库的所有参数的 bean。作为这个 bean 的一部分,对于其中一个参数,我有一个密码密钥,如下例所示,我希望该值应该来自 /vault/password 文件。此 /vault/password 不是 project/application 的一部分。默认情况下,此 /vault/password 将存在于主机中。

applicationContext.xml bean 定义中的语法是什么,用于从应用程序上下文之外的文件中读取值。

<bean class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" id="dataSource">
    <property name="url" value="jdbc:postgresql://postgres:5432/" />
    <property name="username" value="postgres" />
    <property name="password" value="/vault/password" />
</bean>

像这样的东西可能是你最好的选择:

How to correctly override BasicDataSource for Spring and Hibernate

PROBLEM:

Now I need to provide custom data source based on server environment (not config), for which I need to calculate driverClassName and url fields based on some condition.

SOLUTION:

Create a factory (since you need to customize only the creation phase of the object, you don't need to control the whole lifetime of it).

 public class MyDataSourceFactory {
    public DataSource createDataSource() {
        BasicDataSource target = new BasicDataSource();
        if (condition) {
            target.setDriverClassName("com.mysql.jdbc.Driver");                
            target.setUrl("jdbc:mysql://localhost/test?relaxAutoCommit=true"); 
        } else { ... }
        return target;
    }
}

在您的情况下,您的自定义会做一些 I/O 来设置 target.password