我有一个基于 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/