如何在Spring中创建默认的可重写组件? [英] How to create a default overridable Component in Spring?

查看:69
本文介绍了如何在Spring中创建默认的可重写组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除非用户创建其他实现,否则我将尝试创建一个将为AutowiredComponent. 我使用以下代码来尝试解决问题:

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:

界面:

public interface A {...}

实现:

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

使用代码:

public class AUsage {
    @Autowired
    private A a;
}

在此示例中,我没有将AImpl自动装配到AUsage中. 如果我在没有ConditionalOnMissingBean的另一个类中实现了A,则可以正常工作.

In this example, I don't get AImpl autowired into AUsage. If I implement A in another class without the ConditionalOnMissingBean it works.

推荐答案

我尝试从Internet复制@ConditionalOnMissingBean的现有用法,并注意到它们都引用了@Bean方法.

I tried copying existing uses of @ConditionalOnMissingBean from the internet and noticed that they all reference a @Bean method.

确实,当我将此代码添加到AUsage:

Indeed, when I added this code to AUsage:

public class AUsage {
    @Autowired
    private A a;

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

并从AImpl中删除了注释:

and removed the annotations from AImpl:

public class AImpl implements A {...}

一切正常.

如果有人知道,我很乐意对此做一个解释.

I'd be pleased to get an explanation to this, if anyone knows.

这篇关于如何在Spring中创建默认的可重写组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆