how can i get database password at runtime before connecting to the database

java

Solution

Yes, you can, and the key to this is Springs `PropertyPlaceholderConfigurer`.

For example, you create a file on your file system called `database.properties`, containing your password (note, that you can also add more settings to this file, like username, JDBC url, etc).

jdbc.password=1234

Next, you need to declare a `PropertyPlaceholderConfigurer` bean and point it to the `database.properties` file:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>path/to/database.properties</value>
    </property>
</bean>

Note that the path is interpreted as a classpath resource, unless it is prefixed with `file:`.

Finally, replace the configuration of your `dataSource` bean: replace

<property name="password" value="1234" />

with

<property name="password" value="${jdbc.password}" />

Problem

in my applicationcontext.xml i have this : ``` <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> ``` here i am connecting with my database : ``` ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); MySQLRdbHelper rdbHelper = (MySQLRdbHelper) ctx.getBean("ManagerSupervisor"); ``` What is want is to NOT read the password "1234" from my applicationcontext.xml and read it from some properties file in my local drive . as this will be running on different machines and every one have different passwords. Can i achieve this . thanks

Original source