spring Dependency Injection (DI) and Inversion of Control (IoC) Autowiring a dependency through XML configuration


Example

Dependencies can be autowired when using the component scan feature of the Spring framework. For autowiring to work, the following XML configuration must be made:

<context:annotation-config/>
<context:component-scan base-package="[base package]"/>

where, base-package is the fully-qualified Java package within which Spring should perform component scan.

Constructor injection

Dependencies can be injected through the class constructor as follows:

@Component
class Bar { ... }

@Component
class Foo {
  private Bar bar;

  @Autowired
  public Foo(Bar bar) { this.bar = bar; }
}

Here, @Autowired is a Spring-specific annotation. Spring also supports JSR-299 to enable application portability to other Java-based dependency injection frameworks. This allows @Autowired to be replaced with @Inject as:

@Component
class Foo {
  private Bar bar;

  @Inject
  public Foo(Bar bar) { this.bar = bar; }
}

Property injection

Dependencies can also be injected using setter methods as follows:

@Component
class Foo {
  private Bar bar;

  @Autowired
  public void setBar(Bar bar) { this.bar = bar; }
}

Field injection

Autowiring also allows initializing fields within class instances directly, as follows:

@Component
class Foo {
  @Autowired
  private Bar bar;
}

For Spring versions 4.1+ you can use Optional for optional dependencies.

@Component
class Foo {

    @Autowired
    private Optional<Bar> bar;
}

The same approach can be used for constructor DI.

@Component
class Foo {
    private Optional<Bar> bar;

    @Autowired
    Foo(Optional<Bar> bar) {
        this.bar = bar;
    }
}