Skip to content

Explain difference between and pros/cons of dependency injection vs dependency lookup [SPR-3786] #8466

@spring-projects-issues

Description

@spring-projects-issues

Chris Lee opened SPR-3786 and commented

Up until Spring 2.1, the primary (out-of-the-box) mechanism for wiring beans together was dependency injection (DI); I'm including XML-based autowiring as a means of DI as it is external from the code.

With Spring 2.1 and the addition of @Autowired and @Resource, users may (at least initially) think that these are a straight replacement for XML configuration (they can be in some cases), and that these annotations are DI - in fact, these are dependency lookup mechanisms.

These annotations encourage dependency lookup within the code (by name, type or other qualifier), which has pros/cons that should be explained so users can make an informed decision.

Some pros/cons:

Dependency lookup can simplify the wiring of collaborators under certain circumstances;
Dependency lookup promotes a tight-coupling of components (read: increased fragility); remember all those EJB 2.x JNDI lookups?
Dependency injection externalizes & centralizes the wiring of collaborators, promoting loose coupling between components;
Dependency injection is non-intrusive, requiring no additional dependencies in the code;
Dependency lookup requires extra plumbing to process lookups and perform the injection; this may complicate integration testing;


Affects: 2.1 M3

Referenced from: commits dcf0244

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions