views:

122

answers:

3

We have a connection pooling comeponent(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.

+2  A: 

http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

multiple approaches are available, the article above provides more details

 ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
 Class.getResourceAsStream ("/some/pkg/resource.properties");
 ResourceBundle.getBundle ("some.pkg.resource");
Aaron Saunders
A: 

Just load the properties from file, something like

Properties properties = new Properties();
InputStreamReader in = null;
try {
     in = new InputStreamReader(new FileInputStream("propertiesfilepathandname"), "UTF-8");
     properties.load(in);
} finally {
     if (null != in) {
         try {
             in.close();
         } catch (IOException ex) {}
     }
}

Note how the encoding is explicitly specified as UTF-8 above. It could also be left out if you accept the default ISO8859-1 encoding, but beware with any special characters then.

Joonas Pulakka
A: 

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
     ...
}
Alexander Pogrebnyak