Reputation: 2184
import com.google.inject.Injector;
import static com.google.inject.Guice.createInjector;
public final class BatchFactory {
private static class Holder {
private static final Injector INJECTOR = createInjector(new BatchModule());
private static final batchProvider PROVIDER_INSTANCE = INJECTOR
.getInstance(BatchProvider.class);
}
public static BatchProvider getProviderInstance() {
return Holder.PROVIDER_INSTANCE;
}
}
public class BatchModule extends AbstractModule {
@Override
protected void configure() {
bind(BatchProvider.class).to(
BatchProviderImpl.class);
}
}
BatchProvider
is the Interface and BatchProviderImpl
is the class implementation.
Here I am using a class BatchFactory to create the @Singleton
instance of BatchProviderImpl
class.
Can I use @Singleton annotation of google guice to make BatchFactory
class @Singleton
Upvotes: 1
Views: 6317
Reputation: 10695
See the duplicate question, you can do
bind(Service.class).to(ServiceImpl.class).in(Singleton.class);
Or:
@Provides @Singleton
public ServiceImpl providesService() {
return new ServiceImpl();
}
Upvotes: 3