How to access environment-specific configuration in an enterprise application?

My application is a generic enterprise application which can be deployed on any application server running on any OS.

I don’t know how/where to configure my application, except for the database information which are stored in the application server as datasource.

While it’s easy to do, I could use the database as a configuration container, but… the database shouldn’t contain the configuration elements: I want to be able to use any database in any environment (dev, test, acceptance, production).

Does Java EE offer any kind of configuration management similar to what is offered to the datasources? If yes, what is it? If not, what is the best practice on this?

I often read the following advice: put these items in a properties file on the server. Fine, but in that case the location to the properties file becomes a configuration item in itself, so where/how do I define the location of that properties file and transmit that info to my application?

There are a couple options that present themselves in this case.

The first, is the properties file. Its location is somewhere and typically in the class path. Typically, you will see it coupled with the getResource family of calls.

Properties prop = new Properties();

Now, if you don’t have the property file in the classpath, you could specify it in the system properties which can be accessed through the System class as described here.

With the invocation of: java -Dtest="true" -jar myApplication.jar the value can be extracted with: System.getProperty("test") and then used either to specify other resources or being a resource itself. While it isn’t immediately visible with many application servers, its still there, somewhere. In Eclipse, you can easily see them by going to the run configuration and look at the VM arguments.

Similar to the system properties, there are the environment properties accessed through System.getenv. The rest of that set of documents is a good read – The Platform Enviroment. While it speaks mostly to Java SE, nearly everything in it is still applicable and an option for Java EE (I don’t think you’ll be looking at Java Web Start or Java applets).

Moving to the realm of the application server, we get to the names stored in the context of the application or server.

InitialContext ic = new InitialContext();
loc = (String) ic.lookup("java:com/env/app/location");

This value is actually stored in the server configuration itself. The documentation for tomcat. Note that each app server is different and you might get some ugliness in there. The only difference between the database from JNDI and a string is the type that it presents. One is a DataSource, the other is a String.


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *