0

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.

samshers
  • 1
  • 6
  • 37
  • 84
  • Does this answer your question? [Spring fallback bean implementation](https://stackoverflow.com/questions/27735751/spring-fallback-bean-implementation) – Daniel Jacob Aug 31 '20 at 11:04
  • It would be good to describe your specific reasons that could make it impossible to instantiate `A`. – Steven Aug 31 '20 at 11:11

2 Answers2

1

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.

Milgo
  • 2,617
  • 4
  • 22
  • 37
1

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.

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97