Guice学习之Bindings

来源:互联网 发布:看韩剧用什么软件 编辑:程序博客网 时间:2024/06/02 10:36

 Guice学习之Bindings


Binding is perhaps the most important part of the dependency injection.Binding defines how to wire an instance of a particular object to an implementation. 

Linked bindings

Linked binding helps usmap a type to its implementation. This could be of the following type:
An interface to its implementation
A super class to a sub class.
Let us have a look at the FlightSupplier interface:


public interface FlightSupplier {Set<SearchResponse> getResults();}

Following binding declaration binds an interface against its implementation.
Here,
FlightSupplier is bound to theCSVSupplier instance:


bind(FlightSupplier.class).to(CSVSupplier.class);


In case binding to a different implementation ofFlightSupplier,XMLSupplier
is required, we need to simply change the binding:


bind(FlightSupplier.class).to(XMLSupplier.class);

What if you try to provide both the declarations for both the
implementations in FlightEngineModule? This would actually
result in a configuration error, which says that a binding to
FlightSupplier is already present in FlightEngineModule.


Instance bindings


A particular type could bebound to a specific instance of that type. This is
a preferred strategy to inject the value objects. These objects do not have any
dependencies and could be directly injected.


class ClientModule extends AbstractModule{@Overrideprotected void configure() {bind(SearchRequest.class).toInstance(new SearchRequest());}}


Any kind of objects which requires a lot of time to be instantiated should not be configured using .toInstance(). This could have an adverse effect on the startup time.


Untargeted bindings


Untargeted bindings form an interesting part. These are actually indications to injector about a type so that the dependencies are prepared eagerly. Consider a case where in we declare something like this in CSVSupplierModule:

bind(String.class).toInstance("./flightCSV/");


The injector would eagerly prepare an instance of String class with a value
of
./flightCSV/. In case it receives a dependency injection scenario where in it
requires, to inject an instance of String, it would inject this particular instance.

There arises a question: what would be the usefulness of such eagerly
prepared dependencies? The answer lies in the fact that bindings could
be created without specifying a target. This is useful for concrete classes
and types annotated by @ImplementedBy or @ProvidedBy.




Constructor bindings


This type of binding helps tobind a type to a constructor. This particular case arises when we cannot use constructor injection. This is a typical case when:
We are using third-party classes
Multiple constructors for a particular type are participating in dependency injection


读书笔记:Learning Google Guice

0 0