java - 将文件中的值读取到 applicationContext.xml 文件中

标签 java spring applicationcontext

我有一个基于 Spring 的 Web 应用程序,在我的应用程序上下文 xml 文件中,我定义了一个 bean,它具有连接到数据库的所有参数。作为此 bean 的一部分,对于其中一个参数,我有一个密码 key ,如下面的示例所示,我希望该值应来自/vault/password 文件。此/vault/password 不是项目/应用程序的一部分。默认情况下,此/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

关于java - 将文件中的值读取到 applicationContext.xml 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58510364/

相关文章:

java - Files.createDirectory的返回值有什么用

java - Spring Boot与Kafka : How to write unit Integration tests excluding kafka configuration

java - 事务的强制回滚会导致嵌套事务也回滚吗?

java - 加载属性文件会产生奇怪的行为

java - 元素 "http"的前缀 "http:conduit"未绑定(bind) - 这是什么意思?

java - 在 Spring 的构造函数参数中从类路径读取文件时出现 FileNotFound 异常

java - 如何验证 Java 中的字符串是否为有效 URL?

java - 属性和环境始终为空

java - 远程网络服务

java - Tomcat (7&8) : use outgoing http proxy for certain servers