4

在我的 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”,而是从我本地驱动器中的某些属性文件中读取它。因为这将在不同的机器上运行,并且每台机器都有不同的密码。

我能做到这一点。

谢谢

4

3 回答 3

5

是的,你可以,关键是 Springs PropertyPlaceholderConfigurer

例如,您在文件系统上创建一个名为 的文件database.properties,其中包含您的密码(请注意,您还可以向该文件添加更多设置,例如用户名、JDBC url 等)。

jdbc.password=1234

接下来,您需要声明一个PropertyPlaceholderConfigurerbean 并将其指向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}" />
于 2013-04-19T06:30:51.260 回答
0

您可以使用配置文件:

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

 <bean id="database1" profile="dev1"/>
 <bean id="database2" profile="dev2">
于 2013-04-19T06:39:24.467 回答
0

最好的方法是在应用服务器中创建数据源并在 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>
于 2013-04-19T06:54:48.857 回答