如何在Spring中创建默认的可重写组件? [英] How to create a default overridable Component in Spring?
问题描述
除非用户创建其他实现,否则我将尝试创建一个将为Autowired
的Component
.
我使用以下代码来尝试解决问题:
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屋!