Dependency Injection

Dependency Injection

Spring Container

Core component of Spring which is responsible for managing bean lifecycle.

Injection

Annotations

@Lazy

Instantiates bean only when required.

 ...
 @Autowired
    public A(@Lazy B b) {
        this.b = b;
    }
...

@DependsOn

Specified dependency explicitly to control order of instantiation.

@Component
@DependsOn("b")
public class A {
    private final B b;   
}

Cyclic Dependency

What does Spring do?

When a cyclic dependency is detected, Spring automatically uses Early Reference Resolution to partially initialize beans by injecting a proxy, and injecting the actual dependency later.

What can you do using Spring features?

In case of circular dependencies, the behavior depends on the kind of Dependency Injection mechanism you use.

Use Setter Injection

In such cases, Constructor Injection will causes BeanCurrentlyInCreationException - should be avoided.

Setter Injection or Field Injection allow Spring to break down the injection into a two-step process to resolve the dependencies:

  1. Instatiation: Spring instantiates the beans without the dependencies.
  2. Injection: Spring injected the (already initialized) dependencies.

Field Injection is anyway discouraged, so use Setter Injection as a best practice.

@Lazy annotation

Can help manage dependencies by delaying the initialization until the bean is actually needed.

@DependsOn annotation

Doesn't necessarily resolve circular dependency but can help in specifying order of instatiation.


Children
  1. Bean