简体   繁体   中英

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

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

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}" />

You could use profiles:

 GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
 ctx.getEnvironment().setActiveProfiles("dev1");
 ctx.load("*Context.xml");
 ctx.refresh();

 <bean id="database1" profile="dev1"/>
 <bean id="database2" profile="dev2">

The best way is to create the data source in application server and configure as below in application.xml

  <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
     <property name="jndiName"><value>YourDSName</value></property>
  </bean>

  <bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
      .....
   </bean>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM