策略的Java Web应用程序的配置 [英] Strategies for java webapp configuration

查看:161
本文介绍了策略的Java Web应用程序的配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的web应用程序的一部分涉及上传图像文件。对生产服务器,文件将需要被写入/ somepath_on_production_server /图像。对于地方发展,我想将文件写入/ some_different_path /图像。

什么是处理这些配置差异的最佳方式?

一个重要的要求是这样的:我不希望有与生产服务器乱可言,我只是想能够部署一个WAR文件,它的工作。所以我不希望使用它会要求我的环境变量/类路径中的/ etc混乱的技术。在生产机器。我很好的设置我的本地机器虽然。

我imaginine两种可能的一般方法:


  1. 加载一个特殊的开发的配置在运行时的文件,如果某些条件得到满足(环境变量/类路径中的/ etc)

  2. 在构建过程扳动开关(Maven的配置文件也许?)


解决方案

像一个简单的事情,字符串可以声明为的环境条目的中的web.xml ,并通过JNDI获得。下面,用 ENV-条目命名为的ImagePath的例子。

 < ENV输入>
    < ENV-入门名称>&的ImagePath LT; / ENV-入门名称>
    < ENV-入门值与GT; / somepath_on_production_server /图片< / env的入境值>
    < ENV项类型>&java.lang.String中LT; / env的项类型>
< / env的输入>

从Java code访问属性,做JNDI查找:

  //获取的句柄JNDI环境命名上下文
上下文ENV =(上下文)新的InitialContext()查找(的java:c​​omp / env的);//获取单个值
字符串的ImagePath =(字符串)env.lookup(的ImagePath);

这是典型的做法老式的ServiceLocator 在这里你能缓存为给定键的值。

另一种选择是使用一个属性文件


和Maven的方式来处理多个环境通常包括配置文件和过滤(无论是属性文件甚至 的web.xml )。

资源

Part of my webapp involves uploading image files. On the production server, the files will need to be written to /somepath_on_production_server/images. For local development, I want to write the files to /some_different_path/images.

What's the best way to handle these configuration differences?

One important requirement is this: I don't want to have to mess with the production server at all, I just want to be able to deploy a war file and have it work. So I don't want to use any technique which will require me to mess with the environment variables/classpath/etc. on the production machine. I'm fine with setting those on my local machine though.

I'm imaginine two possible general approaches:

  1. loading a special "dev" configuration file at runtime if certain conditions are met (environment variable/classpath/etc)
  2. flipping a switch during the build process (maven profiles maybe?)

解决方案

Simple things like a String can be declared as environment entries in the web.xml and obtained via JNDI. Below, an example with an env-entry named "imagePath".

<env-entry> 
    <env-entry-name>imagePath</env-entry-name> 
    <env-entry-value>/somepath_on_production_server/images</env-entry-value> 
    <env-entry-type>java.lang.String</env-entry-type> 
</env-entry>

To access the properties from your Java code, do a JNDI lookup:

// Get a handle to the JNDI environment naming context
Context env = (Context)new InitialContext().lookup("java:comp/env");

// Get a single value
String imagePath = (String)env.lookup("imagePath");

This is typically done in an old fashioned ServiceLocator where you would cache the value for a given key.

Another option would be to use a properties files.


And the maven way to deal with multiple environments typically involves profiles and filtering (either of a properties file or even the web.xml).

Resources

这篇关于策略的Java Web应用程序的配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆