java - sharing object across different classes -
i need "design" advise. have static jdbc objects , "main entry class" shared among other classes.
my mainclass
looks this:
public static jdbc db1; public static jdbc db2; connectdb(makedirectconnection) // depending on runtime passed argument public static connectdb(boolean makedirectconnection) { if(makedirectconnection) // use direct connection db1 = jdbcfactory.getinstance("db/config/main/db1.properties"); db2 = jdbcfactory.getinstance("db/config/main/db2.properties"); } else { // connect using via ssh tunnel (different host , port) db1 = jdbcfactory.getinstance("db/config/tunnel/db1.properties"); db2 = jdbcfactory.getinstance("db/config/tunnel/db2.properties"); }
jdbcfactory
maintains map
of instances.
it kinda works ok, if want make unit test classes db1
or db2
being used null pointer exception if unit test don't mainclass.dbconnect()
make thing worse - test classes need 1 more different db setup, test.class
do:
main.db1 = jdbcfactory.getinstance("db/config/test/db1.properties");
all it's messy , don't like. isn't there nicer approach how share db1
, db2
?
also boolean makedirectconnection
defined java run argument stops me using final
db1
, db2
. advice how workaround this? (it depends on environment program executed - don't want make dependable on hostname or other os thing.
since need set default instance diffrently testing , deployment. create property file mentiones file should used create default instance db1
, db2
.
to remove need of calling mainclass.dbconnect()
unit test code, create static block , here initlize db1
, db2
default. e.g. if property file defaultdb.properties
, having following content:
db1=db/config/test/db1.properties db2=db/config/test/db2.properties
then use following:
static private properties prop; static { prop = new properties(); prop.load(new fileinputstream("defaultdb.properties")); db1 = jdbcfactory.getinstance(prop.getproperty("db1")); db2 = jdbcfactory.getinstance(prop.getproperty("db2")); }
Comments
Post a Comment