3

I'm having a Java web application designed as a three-tier architecture. Currently I have two different database layers. All of my Data Acces Layer code is in concentrated in a package. The desired data layer is defined in a config file. So another package should be imported depending on a configuration file. Both datalayers communicate with the business layer through a DBfacade object. Is it possible to decide which package that should be imported or should I rename my DBfacades so I have 2 different names and import both packages?

Jeremy Knees
  • 652
  • 1
  • 7
  • 21
  • 5
    There are no conditional package imports in Java. Based on your problem description I would recommend you start reading up on Inversion of Control (IOC). – Perception Mar 20 '13 at 11:55

3 Answers3

2

You are using very bad design, if you are making 2 classes with same name and same method signatures in separate packages, and you are switching between this implementations by changing import. Very bad design.

Note that import section exists ONLY until compile. Then you have fully qualified references in bytecode.

Use interfaces and implementations, swich between implementations using IoC or reflection. Or import both implementations and decide which one to invoke via if, but IoC gives you more flexibility (ability to add new implementation without code change, for example).

Danubian Sailor
  • 1
  • 38
  • 145
  • 223
1

import statement itself is processed at compile time, so you cannot "import different package depending on config file".

However you can use different libraries depending on your configuration. For example if you have 2 different implementations of interface Foo: FooOne and FooTwo located in different jar files you can implement factory FooFactory that loads one of the implementations taking configuration from file, e.g.:

public class FooFactory {
    public Foo createFoo() throws Exception{
        Properties props = new Properties();
        props.load("/var/config.properties");
        return Class.forName(props.getProperty("foo.class")).newInstance();
    }
}
AlexR
  • 114,158
  • 16
  • 130
  • 208
0

Does the data layer depend on the environment? If so, look into exposing data sources with JNDI. This would allow the environment to encapsulate the low-level details.

See Why use JNDI for data sources.

Community
  • 1
  • 1
Zack Marrapese
  • 12,072
  • 9
  • 51
  • 69