title: Spring fallback bean implementation
body: <p>I'm currently trying to configure <strong>Spring Boot</strong> (using <strong>Java Annotations</strong> and <strong>ComponentScan</strong>) for the following scenario:</p>
  
  <p><strong>Scenario</strong></p>
  
  <ul>
  <li>There's an interface <code>MyService</code>.</li>
  <li>I want to provide a default implementation for <code>MyService</code>, let's call it <code>MyDefaultService</code>.</li>
  <li>If the component scan detects no other implementation for <code>MyService</code>, Spring should instantiate <code>MyDefaultService</code> as a "fallback".</li>
  <li>If there is a different implementation of <code>MyService</code> present, let's say <code>MyCustomService</code>, then that bean should <strong>always</strong> take precedence over <code>MyDefaultService</code> when autowiring a dependency to <code>MyService</code>. In that regard, <code>MyDefaultService</code> should be <strong>recessive</strong> (as opposed to <code>@Primary</code>).</li>
  <li>Ideally, there should not need to be an additional annotation on <code>MyCustomService</code> to have it "override" <code>MyDefaultService</code>.</li>
  <li>Ideally, no explicitly implemented factories or factory methods should be required.</li>
  </ul>
  
  <p><strong>Question</strong></p>
  
  <p>The question is: how do I need to annotate the <code>MyDefaultService</code> class in order to achieve this?</p>
  
  <p><strong>What I tried so far to solve the problem</strong></p>
  
  <ul>
  <li>Annotating <code>MyDefaultService</code> with <code>@ConditionalOnMissingBean(MyService.class)</code>. Didn't work because <code>MyDefaultService</code> is never used, even if there is no other implementation of <code>MyService</code>.</li>
  <li>There is an annotation called <code>@Primary</code>that solves the problem. However, it needs to reside on <code>MyCustomService</code>, a class that I try to keep free of additional annotations. Essentially, I need the <em>inverse</em> annotation of <code>@Primary</code> on <code>MyDefaultService</code>. However, I couldn't find such an annotation.</li>
  </ul>
  
  <p><strong>Concrete use case</strong></p>
  
  <p>I am developing a service layer in one project, and a different project will implement a web UI layer on top of it. The UI project has a dependency to the service layer project. However, for certain functionalities implemented at the service layer, I need to know which user is currently logged in at the web context. So I have to define a service interface for that in the service layer project, such that it can be implemented by the UI project. However, for testing purposes in the service-layer project, I need a default implementation of that interface. Also, in case that the UI project team forgets to implement this interface, the app should not crash, but instead instantiate the fallback bean and issue a warning.</p>
  
  <p>Thanks &amp; kind regards,</p>
  
  <p>Alan</p>