orirab
orirab

Reputation: 3353

How to create a default overridable Component in Spring?

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.

Upvotes: 6

Views: 1968

Answers (1)

orirab
orirab

Reputation: 3353

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.

Upvotes: 6

Related Questions