Dependency Injection

com.etdon.commons.di

In order to assist with dependency injection the library provides a simple ServiceProvider that can manage the registration and obtaining of services for you. Currently only one type of ServiceProvider is implemented, the InstanceServiceProvider, which - as the name suggests - handles instances of services. In order to create a ServiceProvider you should use the fluent builder available in the InstanceServiceProvider class:

final ServiceProvider serviceProvider = 
            InstanceServiceProvider.builder()
                        .service(new ExampleService())
                        .selfService()
                        .build();

As shown in the code snippet above services can be registered to a ServiceProvider during the building process however you can also register them later on utilizing the ServiceProvider#register method and its overloads. The #selfService method tells the ServiceProvider to register itself to its own service registry, if this is not something you need you can simply get rid of the call.

In order to obtain a service from a ServiceProvider you can either use the #get or #getOrThrow (including overloads) method:

final ExampleService exampleService = serviceProvider.get(ExampleService.class);

The #get and #getOrThrow methods function similarly however the return value of the former is Nullable while the latter will throw an exception if the service is not present in the registry making it NotNull.

In order to check if a certain services is present in the registry the #has method (including overloads) can be used:

final boolean hasService = serviceProvider.has(ExampleService.class);

In some situations multiple services of the same type might be needed:

final ExampleService importantService = new ExampleService();
final ExampleService otherImportantService = new ExampleService();

For situations like this a string identifier can be provided during the registration and other actions to distinguish between said services. The system internally creates a ServiceIdentifier instance for all services wherever or not they have a string identifier to ensure proper identification.

serviceProvider.register("important", importantService);
serviceProvider.register("otherImportant", otherImportantService);

serviceProvider.has(ExampleService.class, "important");
serviceProvider.has(ExampleService.class, "otherImportant");

serviceProvider.get(ExampleService.class, "important");
serviceProvider.get(ExampleService.class, "otherImportant");

Last updated