[英]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");
企业级的答案是通过像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.