2012-08-01 84 views
1

我在Tomcat 6上部署了基于Java的Web应用程序。我需要将某些属性设置为可配置。目前我已经创建了一个config.properties文件,并在静态属性对象中加载该文件。在Java Web应用程序中使用可配置的属性

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

+0

即使我用一个静态类加载从我的属性文件,我认为是最好的! – Patton 2012-08-01 05:13:53

+0

我同意@Patton – 2012-08-01 05:22:44

+0

可由谁配置?通过操作?由管理员用户通过用户界面? ...? – meriton 2012-08-01 05:26:08

回答

0

试试这个样本;

这是放置在com.package中的示例Resource.properties文件;

 name=John 
    [email protected] 
    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。这sample是在JSF性质的用途。

+0

我已经在使用这个apporach了。这个应用程序的问题是,无论何时向应用程序发出请求(我认为是错误的应用程序),或者我必须将其加载到静态属性对象中,并且在文件更改时它都不会更新,我将不得不重新加载应用程序 – orak 2012-08-01 05:52:08

+0

@orak检查我的编辑帖子。这可能对您有所帮助。 – 2012-08-01 06:53:09

0

另一个选项可能是将一个类的所有常量定义在其中。这将为您提供一种集中的方式,您可以在其中有效且高效地配置应用程序。

然而,我认为使用配置文件是最好的选择,因为(我不认为)每改变一次你就必须重新编译你的代码。

编辑:看到上面的一些评论,你可以做的将是在你的数据库中有一个单独的表,你将能够存储所有的常量。然后,您可以通过后端Web界面将此表提供给系统管理员和其他支持人员。

+0

代码不能在生产环境中重新编译,集中式类不在此处 – orak 2012-08-01 05:35:44

+0

@orak:我这样认为。如果是这种情况,那么你将不得不继续使用配置文件,否则,我建议的后端系统。后端系统的优点是不需要访问机器。 – npinti 2012-08-01 05:39:12

0

企业级解决方案是通过集成框架加载您的配置,如Spring。如果你的应用程序相当小,我不一定会推荐它。

0

与Spring框架加载性能:

<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> 
相关问题