27 Temmuz 2022 Çarşamba

Guice JustInTimeBindings

Giriş
Soru şöyle. Yani Guice bazı nesneleri kendisi otomatik yaratabiliyor. Bu açıdan Jakarta EE ile benzeşiyor.
Q : How does Guice inject classes without an @Inject-annotated constructor?
A : Guice bindings that are not declared in modules are known as Just-in-time Bindings, and by default Guice is willing to call constructors that take zero arguments:
...
If you haven't required explicit bindings and you have a public no-arg constructor, Guice will call it as if you had marked it with @Inject. This is in contrast to Dagger, which will only call @Inject-annotated constructors:
Enforce Explicit Bindings şöyle yapılır
class ExplicitBindingModule extends AbstractModule {
  @Override
  protected void configure() {
    binder().requireExplicitBindings();
  }
}
Örnek
Elimizde şöyle bir kod olsun. Eğer "Enforce Explicit Bindings" yoksa ve DepB no-arg constructor'a sahipse, Guice DepB nesnesini kendiliğinden yaratabilir.
public class ServiceClass {
  @Inject
  public ServiceClass(DepA depA, DepB depB) {
    ...
  }
}

@Provides
public DepA provideDepA() {
 //constructs DepA object and returns it
}



Hiç yorum yok:

Yorum Gönder