Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making the configuration available to all classes

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?

like image 685
Amir Rachum Avatar asked May 17 '11 11:05

Amir Rachum


People also ask

Can we have multiple configuration classes?

One configuration class can import any number of other configuration classes, and their bean definitions will be processed as if locally defined.

What are configuration classes in Java?

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.

What is the @configuration in spring boot?

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.

How can you directly access all classes in the package in Java?

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.


1 Answers

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.

like image 118
alpian Avatar answered Oct 15 '22 18:10

alpian