I need some "design" advise. I have static JDBC objects and my "main entry class" which are shared among other classes.
My MainClass
looks like 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 and 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, but if I want to make unit test for classes where db1
or db2
is being used I get null pointer exception if from unit test I don't do MainClass.dbConnect()
Make thing worse - from test classes I need even one more different DB setup, so from Test.class
I do:
Main.db1 = JdbcFactory.getInstance("db/config/test/db1.properties");
All together it's messy and I don't like. Isn't there some nicer approach how to share db1
and db2
?
Also boolean makeDirectConnection
which is defined from java run argument stops me from using final
db1
and db2
. Any advice how to workaround this? (It depends on environment where program is executed - but I don't want to make it dependable on hostname or some other OS thing.
I would not provide a boolean as the jvm argument to differ between your two (or three) cases. Instead i would provide the db urls via paramter. In that case you can also call your method within your test with the "test-db.properties".
Since you are need to set the default instance diffrently for testing and deployment. So create a property file which mentiones that which file should be used to create default instance for db1
and db2
.
To remove the need of calling MainClass.dbConnect()
from your unit test code, just create a static block and here initlize db1
and db2
with default. eg If property file is defaultDB.properties
and 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"));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.