How to create a default overridable component in Spring?

I am trying to create Componentwhich will be Autowiredif the user does not create another implementation. I used the following code to try to isolate the problem:

Interface:

public interface A {...}

Implementation:

@Component
@ConditionalOnMissingBean(A.class)
public class AImpl implements A {...}

Usage Code:

public class AUsage {
    @Autowired
    private A a;
}

In this example, I am not getting AImplautowired in AUsage. If I implement Ain another class without ConditionalOnMissingBean, it works.

+4
source share
1 answer

I tried to copy existing applications @ConditionalOnMissingBeanfrom the Internet and noticed that they all refer to the method @Bean.

In fact, when I added this code to AUsage:

public class AUsage {
    @Autowired
    private A a;

    @Bean
    @ConditionalOnMissingBean
    public A createA() {
        return new AImpl();
    }
}

and removed annotations from AImpl:

public class AImpl implements A {...}

everything works as expected.

, .

0

Source: https://habr.com/ru/post/1677234/


All Articles