簡體   English   中英

在Java Web應用程序中使用可配置屬性

[英]Using configurable properties in Java web applications

我在Tomcat 6上部署了一個基於Java的Web應用程序。我需要將一些屬性設置為可配置。 目前,我已經創建了config.properties文件,並將該文件加載到靜態Properties對象中。

我想知道是否還有其他有效的方法或框架可以在Java Web應用程序中使用可配置屬性?

您可能擁有的另一種選擇是讓一個類具有在其中定義的所有項目常量。 這將為您提供一種集中式的方式,您可以在其中有效而高效地配置應用程序。

話雖這么說,但我認為使用配置文件是最好的選擇,因為(我不認為)更改后每次都必須重新編譯代碼。

編輯:看到上面的一些評論,您可以做的是在數據庫中有一個單獨的表,您可以在其中存儲所有常量。 然后,您可以通過后端Web界面將該表提供給系統管理員和其他支持人員。

試試這個樣本;

這是放置在com.package中的示例Resource.properties文件。

     name=John
     email=john@company.com
     description=John is a Java software developer

訪問就像這樣;

     private static final String PROPERTIES_FILE = "com/package/Resource.properties";

     Properties properties = new Properties();  
     properties.load(this.getClass().getResourceAsStream(PROPERTIES_FILE));  
     String name = props.getProperty("name");  
     String email = props.getProperty("email");  
     String description = props.getProperty("description");

使用可配置屬性的另一個框架是JSF 。此示例是JSF中屬性的用法。

企業級的答案是通過像Spring這樣的集成框架來加載您的配置。 但是,如果您的應用程序很小,則不一定會推薦它。

使用Spring Framework加載屬性:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:configuration.properties"></property>
    </bean>

    <!-- Here is configutaion for connection pool -->
    <!-- Those ${} properties are from the configuration.properties file -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.user}"/>
        <property name="password" value="${db.pass}"/>
    </bean>

</beans>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM