Java Reference
In-Depth Information
dynamically. A service can be used without ever specifying where the service comes from
or who provides it, which means service-oriented code remains loosely coupled. But the
code for looking up services can be a bit verbose. The code for managing services that
might appear and disappear dynamically is even more long-winded.
If you're not coming from the world of OSG i, you're probably thinking of a differ-
ent solution instead—dependency injection.
2.3.1
Inversion of control
Inversion of control is an elegant programming pattern where required services are
supplied rather than looked up. This is often known as dependency injection, and
occasionally as the Hollywood principle (“don't call us, we'll call you”).
In general, dependency injection refers to a dependency injection container that
wires together managed objects, injecting the dependencies into an object. The
dependency injection container manages the lifecycle of objects, typically supporting
callbacks for initialization and destruction. Figure 2.12 shows the differences between
dependency lookup and dependency injection.
Dependency injection allows applications to be configured differently in different
environments. For example, it's often useful to do unit testing with a lightweight ver-
sion of a required component, possibly even a mocked implementation. Further-
more, as the business expands or requirements change, a different version of the
component can be wired in, one that's more available, or scales better, or one that
has better performance.
Dependency injection extends the loose coupling model to completely externalize
the couplings from the code. Instructions for wiring components together are usually
stored in XML metadata that can be changed relatively easily, without a recompile.
Lookup
Normal control
Consumer
Service
Injection
Inversion of control
Consumer
Service
Container
Figure 2.12 Normal control and inversion of control. In the normal case, the consumer looks up a service
it requires. In the inversion of control model, also known as dependency injection, the consumer is auto-
matically given the service. An application container manages passing the service to the consumer.
Search WWH ::




Custom Search