I'm writing a small web server, and it takes a configuration file with all sorts of different options: how many threads to run, which class deals which each file extension, which file to display by default and so on and so forth. To represent this, I'm parsing the config file into a Configuration
object which contains all these settings, and the main class holds this object.
However, the config data is required on almost every level of the server - classes within classes within classes...
My question is, what is the best practice to use here? Should I give the config as a parameter for many many classes and pass it back and forth? Should I make it a singleton? Is there another solution I don't see?
One configuration class can import any number of other configuration classes, and their bean definitions will be processed as if locally defined.
Class Configuration. A Configuration object is responsible for specifying which LoginModules should be used for a particular application, and in what order the LoginModules should be invoked.
Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.
Class loaders are dynamic. Hence, finding classes in a package is essentially a file system operation rather than one done by using Java Reflection. However, we can write our own class loaders or examine the classpath to find classes inside a package.
Use Guice! Guice is a dependency-injection framework which effectively replaces your use of the new keyword. You define your object bindings in a Module like this:
bind(Configuration.class).to(MySpecificConfiguration.class);
bind(WebServer.class).to(MySpecificWebServerImplementation.class);
And then, instead of newing up WebServer
directly, you just ask Guice to do it for you:
WebServer ws = Guice.createInjector(yourModule).getInstance(WebServer.class);
Which will magically create MySpecificWebServerImplementation
for you. If MySpecificWebServerImplementation
is defined as follows:
public class MySpecificWebServerImplementation {
@Inject
public MySpecificWebServerImplementation(Configuration configuration) {
}
}
Then MySpecificWebServerImplementation
will automatically get given the configuration and you don't have to worry about passing it around.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With