2013-08-22 44 views
0

我有一個可執行Jar,裏面有一個spring項目。 有一個屬性文件爲代碼提供變量,並將與jar存在於相同的目錄中。一切工作正常。在Java代碼中我加載屬性文件:如何動態選擇要使用的數據庫

Properties properties = new Properties(); 
properties.load(new FileInputStream(PROPERTY_FILE_NAME)); 

我在applicationContext.xml數據源是

<bean id="teDataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
    <property name="url" value="jdbc:mysql://localhost:3306/testDB"/> 
    <property name="username" value="t"/> 
    <property name="password" value="t"/> 
    <property name="initialSize" value="5"/> 
    <property name="maxActive" value="10"/> 
</bean> 

的休眠特性是:

<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
    <property name="properties"> 
    <props>  
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
    <!-- <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> --> 
    <prop key="hibernate.jdbc.fetch_size">250</prop>.... 

以上所有的作品都與MySql或Oracle和改變方言(下面的評論道具密鑰)將做交換機。但是現在我希望能夠根據屬性文件中的屬性選擇數據庫。在我的情況下,我該如何實現這一目標?

版本:

spring - 3.0.5.RELEASE 
hibernate - 3.3.2.GA 
+0

退房春譜。 –

+0

@SotiriosDelimanolis難道還有更簡單的解決方案嗎?這個項目的一切都已到位,只是這種切換數據庫的能力 – happybuddha

+1

在啓動應用程序之前更改屬性。 –

回答

2

你應該有地方的一切是你的應用程序(如數據庫配置,服務器的絕對路徑,外部WebService的網址等)依賴於環境的。

這通常可以使用標準Java屬性文件完成。然後,您可以使用PropertyPlaceholderConfigurer加載它,並在需要配置某些內容的bean配置中隨處使用${config.myproperty}樣式。

在應用程序啓動時,您必須爲其指定例如此配置文件的路徑,或者它也可以存在於默認路徑(約定優於配置)。

+0

因此,我需要在appcontext.xml中進行哪些更改。我的目標是讓用戶從屬性文件中選擇一個數據庫,該文件與可執行的jar文件位於相同的目錄中。 – happybuddha

2

你可以使用Maven配置您的身材,輪廓:

<profiles> 
<profile> 
      <id>database1</id> 
      <activation> 
       <activeByDefault>true</activeByDefault> 
      </activation> 
      <build> 
       <filters> 
        <filter>db1.properties</filter> 
       </filters> 
      </build> 
     </profile> 
     <profile> 
      <id>database2</id> 
      <activation> 
       <activeByDefault>false</activeByDefault> 
      </activation> 
      <build> 
       <filters> 
        <filter>db2.properties</filter> 
       </filters> 
      </build> 
     </profile> 
    </profiles> 

在db1.properties文件,你給第一個數據庫中的所有配置,並在db2.properties另一個。

例如,你可以有: database.name = JDBC:MySQL的://本地主機:在db1.properties 3306/testDB1 database.name = JDBC:MySQL的://本地主機:在db2.properties 3306/testDB2

而在你的applicationContext文件,你會只是把這個: 屬性名= 「URL」 值= 「$ {} database.name」

+0

但是這不允許我從屬性文件中的屬性中選擇數據庫,右鍵 – happybuddha

相關問題