简体   繁体   English

如何避免具有相同ID的bean?

[英]How to avoid beans with same id?

I have a problem familiar with this bean override 我有一个熟悉这个bean覆盖的问题

2 beans are with same id, but their package is different. 2个bean具有相同的ID,但它们的包不同。 Bean A was overridden by bean B. I spent lots of time to find the cause. 豆A被豆B覆盖了。我花了很多时间找到原因。

So I want to prevent the case. 所以我想防止这种情况。 My request is that the spring throw a exception then shutdown the process of initializing if encounter case like this. 我的请求是spring抛出一个异常,然后关闭初始化的过程,如果遇到这样的情况。

You can @Inject ( @Autowire ) by type, not by id. 你可以按类型@Inject@Autowire ),而不是id。 Read on Autowiring collaborators . 阅读Autowiring协作者

Spring can't have two beans with the same id in one context. Spring在一个上下文中不能有两个具有相同id的bean。 So solution is obvious - use different ids. 所以解决方案显而易见 - 使用不同的ID。

If you are using xml context it should be : 如果您使用的是xml上下文,那么它应该是:

<bean id="foo" class="what.ever.foo.Class" />

<bean id="bar" class="what.ever.package1.Class" />

If you are using annotations and component scan: 如果您正在使用注释和组件扫描:

@Component("foo")
@Component("bar")

Annotation based context use different method names: 基于注释的上下文使用不同的方法名称:

   @Bean
   public Foo foo() {
      return new Foo();
   }
   @Bean
   public Bar bar() {
      return new Bar();
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM