I am trying to create a Component that will be Autowired unless the user creates a different implementation.
I used the following code to try and isolate the problem:
The interface:
public interface A {...}
The implementation:
@Component
@ConditionalOnMissingBean(A.class)
public class AImpl implements A {...}
The usage code:
public class AUsage {
@Autowired
private A a;
}
In this example, I don't get AImpl autowired into AUsage.
If I implement A in another class without the ConditionalOnMissingBean it works.
I tried copying existing uses of @ConditionalOnMissingBean from the internet and noticed that they all reference a @Bean method.
Indeed, when I added this code to AUsage:
public class AUsage {
@Autowired
private A a;
@Bean
@ConditionalOnMissingBean
public A createA() {
return new AImpl();
}
}
and removed the annotations from AImpl:
public class AImpl implements A {...}
everything works as expected.
I'd be pleased to get an explanation to this, if anyone knows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With