简体   繁体   English

Spring @Bean 名称不同但方法名称相同抛出 Bean 创建异常

[英]Spring @Bean with different name but same method name throws Bean creation exception

New to spring. spring 的新手。
I have defined 2 @Beans with unique names for each but with the same method name.我已经定义了 2 个 @Beans,每个 @Beans 具有唯一的名称,但具有相同的方法名称。 One of the beans are not created and No valid bean exception is thrown.没有创建 bean 之一,并且没有抛出有效的 bean 异常。

@Bean("Example.A") 
public ClassA getNewBean() {
   return new ClassA();
}




@Bean("Example.B")
public ClassA getNewBean() {
  return new ClassA();
}

The second Bean is not created and Exception is thrown as no valid bean exists ClassA.没有创建第二个 Bean,并且由于 ClassA 不存在有效的 bean 而引发异常。

This post has the two beans in different classes, whereas in my case both are within the same @Configuration. 这篇文章有两个不同类的bean,而在我的例子中,它们都在同一个@Configuration 中。

When you inject by bean name , you can use @Resource :当你通过bean name注入时,你可以使用@Resource

@Controller
public class MyController {
    @Resource(name = "Example.A")
    private ClassA obj;

    // ...
}

As an aside, beans should be named by Java standard convention .顺便说一句,bean 应该按照Java 标准约定命名。

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

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