赋值给final字段。
public class RealBillingService implements BillingService { private final CreditCardProcessor processorProvider; private final TransactionLog transactionLogProvider; @Inject public RealBillingService(CreditCardProcessor processorProvider, TransactionLog transactionLogProvider) { this.processorProvider = processorProvider; this.transactionLogProvider = transactionLogProvider; } }
public class PayPalCreditCardProcessor implements CreditCardProcessor { private static final String DEFAULT_API_KEY = "development-use-only"; private String apiKey = DEFAULT_API_KEY; @Inject public void setApiKey(@Named("PayPal API key") String apiKey) {//该方法会被Guice调用并注入值 this.apiKey = apiKey; } }
public class DatabaseTransactionLogProvider implements Provider<TransactionLog> { @Inject Connection connection; public TransactionLog get() { return new DatabaseTransactionLog(connection); } }
public class PayPalCreditCardProcessor implements CreditCardProcessor { private static final String SANDBOX_API_KEY = "development-use-only"; private String apiKey = SANDBOX_API_KEY; @Inject(optional=true) public void setApiKey(@Named("PayPal API key") String apiKey) { this.apiKey = apiKey; } }
@Inject(optional=true) Date launchDate;//launchDate依赖会进行注入
public static void main(String[] args) { Injector injector = Guice.createInjector(...); CreditCardProcessor creditCardProcessor = new PayPalCreditCardProcessor();//手动创建而不是从容器中获取 injector.injectMembers(creditCardProcessor);//会为creditCardProcessor中需要注入的成员进行注入 }
@Override public void configure() { requestStaticInjection(ProcessorFactory.class); ... } class ProcessorFactory { @Inject static Provider<Processor> processorProvider; /** * @deprecated prefer to inject your processor instead. */ @Deprecated public static Processor getInstance() { return processorProvider.get(); } }
七、自动注入(Automatic Injection)
以下情形Guice会进行自动注入:
a.传递给toInstance()语句的实例
b.传递toProvider()语句的Provider对象,这些对象会在注入器创建时进行注入.