Binding Services
The org.nnsoft.guice.gspi.ServiceLoaderModule provides APIs to bind Services to Provided discovered via SPI pattern.
Given an hipotetycal FooService:
package com.acme; public interface FooService { void doSomething(); }
With related implementations:
package com.acme.first; public final class FooServiceImpl1 implements FooService { @Override public void doSomething() { // ... } }
and
package com.acme.second; public final class FooServiceImpl2 implements FooService { @Override public void doSomething() { // ... } }
Then define the SPI in META-INF/services/com.acme.FooService file(s):
# created by Jack Bauer in less than 24h com.acme.first.FooServiceImpl1 com.acme.second.FooServiceImpl2 # EOL comment # comments and blank lines supported #
Then users can:
- Bind the Service to the first discovered Provider
import static com.google.inject.Guice.createInjector; import com.acme.FooService; import com.google.inject.Injector; import org.nnsoft.guice.gspi.ServiceLoaderModule; ... Injector injector = createInjector( new ServiceLoaderModule() { @Override protected void configure() { bindService( FooService.class ).loadingFirstService(); } } );
and the require its injection somewhere else:
public class PowerTool { @Inject private FooService fooService; // setters and algorithms omitted }
- Bind the Service to all discovered Provider
import static com.google.inject.Guice.createInjector; import com.acme.FooService; import com.google.inject.Injector; import org.nnsoft.guice.gspi.ServiceLoaderModule; ... Injector injector = createInjector( new ServiceLoaderModule() { @Override protected void configure() { bindService( FooService.class ).loadingAllService(); } } );
and the require their injection somewhere else:
public class SuperPowerTool { @Inject private Set<FooService> fooService; // setters and algorithms omitted }
Eh?!? Just that?!? YES!!! :)