Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a default overridable Component in Spring?

Tags:

java

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.

like image 263
orirab Avatar asked May 16 '17 08:05

orirab


1 Answers

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.

like image 66
orirab Avatar answered Nov 10 '22 03:11

orirab