使用guice在java中创建Singleton

时间:2018-01-09 18:49:33

标签: java singleton guice

self.navigationItem.hidesBackButton = true

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是类实现。

这里我使用类BatchFactory来创建BatchProviderImpl类的@Singleton实例。

我可以使用google guice的@Singleton注释来BatchProviderImplBatchFactory

1 个答案:

答案 0 :(得分:1)

请参阅duplicate question,您可以

bind(Service.class).to(ServiceImpl.class).in(Singleton.class);

或者:

@Provides @Singleton
public ServiceImpl providesService() {
    return new ServiceImpl();
}