您可以使用以下类型的代码来执行您想要的操作:
class ServiceModule extends AbstractModule {
private TestClass readTestClassFromFile() {
return new TestClass();
}
// Cache an instance for 5 seconds.
private final Supplier<TestClass> testClassSupplier = Suppliers.memoizeWithExpiration(this::readTestClassFromFile, 5, SECONDS);
@Provides TestClass provideTestClass() { // Don't declare as singleton
return testClassSupplier.get();
}
}
然后,在你的课堂上:
class Service {
@Inject
Provider<TestClass> testClassProvider; // Inject the provider, not the instance itself, or any supplier.
void doSomething() throws Exception {
TestClass a = testClassProvider.get();
TestClass b = testClassProvider.get();
Thread.sleep(6000); // Sleep for 6 seconds
TestClass c = testClassProvider.get();
System.out.println(a == b); // Prints true
System.out.println(a == c); // Prints false
}
}
您请求了一种通用的方法,所以在这里,检查bindSupplier
方法:
import static com.google.common.base.Suppliers.memoizeWithExpiration;
import com.google.inject.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) throws Exception {
Guice.createInjector(new ServiceModule())
.getInstance(Service.class)
.doSomething();
}
static class ServiceModule extends AbstractModule {
Dependency createDependency() { return new Dependency(); }
// For Java 8+
private <T> void bindSupplier(Class<T> type, Supplier<? extends T> supplier) {
// Definitely avoid .in(Singleton.class) because you want the scope to be defined by the Supplier.
bind(type).toProvider(supplier::get);
}
// For Java 7 and less
// private <T> void bindSupplier(Class<T> type, final Supplier<? extends T> supplier) {
// bind(type).toProvider(new Provider<T>() {
// @Override public T get() { return supplier.get(); }
// });
// }
@Override protected void configure() {
bindSupplier(Dependency.class,
memoizeWithExpiration(this::createDependency, 3, TimeUnit.SECONDS));
}
}
static class Dependency {}
static class Service {
@Inject Provider<Dependency> dependencyProvider;
void doSomething() throws InterruptedException {
Dependency a = dependencyProvider.get();
Dependency b = dependencyProvider.get();
Thread.sleep(4000);
Dependency c = dependencyProvider.get();
System.out.printf("a == b ? %s%n", a == b); // true
System.out.printf("a == c ? %s%n", a == c); // false
}
}
}