Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

java - How a JAR file can read an external properties file

We have a connection pooling component (JAR file) for one of our application. As of now the application connection details are bundled with-in the JAR file (in .properties file).

Can we make it more generic? Can we have the client tell the properties file details (both the path and the file name) and use the JAR to get the connection?

Does it make sense to have something like this in the client code:

XyzConnection con = connectionIF.getConnection(uname, pwd);

Along with this, the client will specify (somehow???) the properties file details that has the URLs to connect, timeout etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simplest way, use the -D switch to define a system property on a java command line. That system property may contain a path to your properties file.

E.g

java -cp ... -Dmy.app.properties=/path/to/my.app.properties my.package.App

Then, in your code you can do ( exception handling is not shown for brevity ):

String propPath = System.getProperty( "my.app.properties" );

final Properties myProps;

if ( propPath != null )
{
     final FileInputStream in = new FileInputStream( propPath );

     try
     {
         myProps = Properties.load( in );
     }
     finally
     {
         in.close( );
     }
}
else
{
     // Do defaults initialization here or throw an exception telling
     // that environment is not set
     ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...