如何仅使用注释按名称覆盖Spring Service Bean [英] How to overwrite Spring service beans by name, using annotations only

查看:388
本文介绍了如何仅使用注释按名称覆盖Spring Service Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我将Spring bean配置为

Given I have a Spring bean configured as

@Service("myService")
public class DefaultService extends MyService {
}

和使用此bean的类

public class Consumer {
    @Autowired
    @Qualifier("myService")
    private MyService service;
    ...
}

我现在希望我的项目(包括前面的类)具有Consumer另一个MyService实现的注入.因此,我想覆盖bean myService

I now want my project, that includes the preceding classes, to have Consumer another implementation of MyService being injected. Therefore I would like to overwrite the bean myService

@Service("myService")
public class SpecializedService implements MyService {
}

现在导致Consumer携带SpecializedService而不是DefaultService的实例.根据定义,我在Spring容器中不能有两个具有相同名称的bean.我怎样才能告诉Spring,新服务的定义将覆盖旧服务?我不想修改Consumer类.

resulting in Consumer carrying now an instance of SpecializedService instead of DefaultService. By definition I cannot have two beans with the same name in the Spring container. How can I tell spring, that the definition of the new service shall overwrite the older one? I don't want to modify the Consumer class.

推荐答案

要么明确定义服务bean

Either define the service bean explicitly

<bean id="myService" class="x.y.z.SpecializedService" />

或对其进行组件扫描.

在任何情况下,在您的应用程序上下文中,请避免显式定义DefaultService并避免对其进行组件扫描.

In either event, in your application context, avoid explicitly defining DefaultService and avoid component-scanning it.

这篇关于如何仅使用注释按名称覆盖Spring Service Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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