在我的 applicationcontext.xml 中我有这个:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/dashboardsupervisor" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
这里我正在连接我的数据库:
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
MySQLRdbHelper rdbHelper = (MySQLRdbHelper)
ctx.getBean("ManagerSupervisor");
我想要的是不要从我的 applicationcontext.xml 中读取密码“1234” 并从我本地驱动器中的一些属性文件中读取它。 因为这将在不同的机器上运行,并且每台机器都有不同的密码。
我能做到吗?
谢谢
最佳答案
是的,你可以,关键是 Springs PropertyPlaceholderConfigurer
。
例如,您在文件系统上创建一个名为 database.properties
的文件,其中包含您的密码(请注意,您还可以向该文件添加更多设置,例如用户名、JDBC url 等).
jdbc.password=1234
接下来,您需要声明一个 PropertyPlaceholderConfigurer
bean 并将其指向 database.properties
文件:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>path/to/database.properties</value>
</property>
</bean>
请注意,路径被解释为类路径资源,除非它以file:
为前缀。
最后,替换 dataSource
bean 的配置:replace
<property name="password" value="1234" />
与
<property name="password" value="${jdbc.password}" />
关于java - 在连接到数据库之前如何在运行时获取数据库密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16098530/