Does Spring DI have a fall back mechanism?

357 Views Asked by At

Does Spring DI have a fall back mechanism ?
What I mean by above is, if a bean A instantiation is not possible for some reason, then can a bean B be instantiated and auto-wired automatically.

The use case is - in testing, if db bean can't be instantiated due to network connectivity. I want a mock bean to be injected.

2

There are 2 best solutions below

0
On

You can use @Autowired(required = false) for class A and B and check in a @PostConstruct method if either A or B are initialized. But I don't know any mechanism to only use @Autowired if an other @Autowired failed.

0
On

You should separate the concepts of bean instantiation and autowiring.

If a class A defined as a bean (for example by putting a @Component on it) cannot be instantiated for some reason the application context won't start, period. This is regardless the dependencies of the bean itself.

Now, if you have beans A and beans B and bean C that has two "candidates" for auto-wiring , then it looks like this:

public interface I {}

@Component
public class A implements I {}

@Component
public class B implements I {}

@Component
public class C {
   @Autowired  
   private I i;
}

In this case class C won't be instantiated and the whole Application Context will fail because spring won't know which implementation you'll have to use in class C (two candidates for autowiring).

In this case you need to give hints to Spring:

  • by using @Primary annotation
  • by using @Qualifier annotation

So to wrap-up the process of initialization of Application Context must be deterministic and well defined.