Multiple .properties files in a Java project

2019-08-29 11:37发布

问题:

I would like to find an expedient way to switch between multiple .properties files for different deployment configurations.

My initial inclination is to create a separate file, selector.properties, whose single property is used to determine the proper file:

properties.file=deploymentConfiguration1.properties

...for one deployment, or:

properties.file=deploymentConfiguration2.properties

...for the next deployment.

Another developer on my team has an ApplicationProperties class wherein:

private static final String PROP_FILE="someFileName.properties";

...is the means to do this. However, I want to switch properties files without rebuilding! Thanks in advance for your input.

EDIT: Maybe I should have been more clear initially, but this is for a set of web services packaged as an AAR. I will just drop it into the web server and let Tomcat and Axis2 do their thing.

So, I don't think some of the answers with command-line params will work in this context.

回答1:

Have multiple property files, one per env, eg;

application-dev.properties
application-test.properties
application-prod.properties

Launch your app with the env as a system property;

java -Denv=test

Load your properties from the relevant file;

String props = "application-" + System.getProperty("env") + ".properties";

Note that I'd generally discourage this in favour of a properties file with a fixed name where the file is generated at build time.

Edit:
If it's a web app, you can set the value of env in the deployment descriptor (web.xml)

<env-entry>
  <env-entry-name>myEnv</env-entry-name>
  <env-entry-type>java.lang.String</env-entry-type>
  <env-entry-value>test</env-entry-value>
</env-entry>

then you can get the value in your web app like this;

Context ctx = new InitialContext();
Context envCtx = (Context) ctx.lookup("java:comp/env");
String env = (String)envCtx.lookup("myEnv");
String props = "application-" + env + ".properties";


回答2:

Add a argument that points out the configuration file!

java Program -config deploymentConfiguration2.properties


回答3:

The approach of using a "property manager" property file sounds good. The master property file could be passed as a parameter to the vm via a jvm argument But one downside of this process is that the master property file becomes unmanaged over a period of time. For example you may end up retaining some old property file references which no longer makes sense.