我认为您在谈论懒惰地创建bean。默认情况下是这样(除非您使用 toInstance 绑定):
package com.sopovs.moradanen;
import javax.inject.Singleton;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class Main {
public static void main(String[] args) {
System.out.println("Creating injector");
Injector injector = Guice.createInjector();
System.out.println("Injector created");
System.out.println("Getting instance of Foo");
injector.getInstance(Foo.class);
System.out.println("Got instance of Foo");
System.out.println("Getting instance of Bar");
injector.getInstance(Bar.class);
System.out.println("Got instance of Bar");
System.out.println("Getting another instance of Foo");
injector.getInstance(Foo.class);
System.out.println("Got another instance of Foor");
}
@Singleton
public static class Foo {
public Foo() {
System.out.println("Foo Created");
}
}
@Singleton
public static class Bar {
public Bar() {
System.out.println("Bar Created");
}
}
}
输出是:
Creating injector
Injector created
Getting instance of Foo
Foo Created
Got instance of Foo
Getting instance of Bar
Bar Created
Got instance of Bar
Getting another instance of Foo
Got another instance of Foor