airlift / airline

Java annotation-based framework for parsing Git like command line structures
Apache License 2.0
846 stars 138 forks source link

di-support #33

Open staenker opened 10 years ago

staenker commented 10 years ago

I extracted ParserUtil.createInstance into a Factory interface. This is configurable using the builder. The default Implementation is using the logic from the old createInstance method in ParserUtil. This way, the change is fully backwards compatible but allows users to implement and provide their own factory implementation. This enables them to use Guice or Spring DI containers to instatiate their commands. In Short: I added dependency injection support. An example Factory for Google Guice Support would look like this:

public class GuiceCommandFactory implements CommandFactory {
    private final Injector injector;

    public GuiceCommandFactory(Injector injector) {
        this.injector = injector;
    }

    @Override
    public <T> T createInstance(Class<T> instanceClass) {
        return injector.getInstance(instanceClass);
    }
}

An example cli main class would look like this:

final Injector injector = Guice.createInjector(new GuiceModule(transferNetworkConfiguration));
Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("devlab")
                                      .withCommandFactory(new GuiceCommandFactory(injector))
                                      .withDescription("the development network automation tool")
                                      .withDefaultCommand(Help.class)
                                      .withCommands(Help.class);
Cli<Runnable> devlabParser = builder.build();
devlabParser.parse(args).run();

The next step would be to provide The Factory Implementations for the various di frameworks but that would mean adding dependencies to those frameworks which will be inherited by any projects using this library. A better approach would be to convert this project to a maven multi module project and add one module for each Factory. Third option would be to update the documentation and leave the Factory implementation up to the user. Which is your preferred option?

jvanzyl commented 9 years ago

I think we did something similar and my changes were just merged into master. If there's anything missing in my commits maybe we can sort that out, get your changes added if required and close this.