【问题标题】:Spring @Bean with different name but same method name throws Bean creation exception名称不同但方法名称相同的Spring @Bean抛出Bean创建异常
【发布时间】:2021-02-04 21:53:23
【问题描述】:

春天的新手。
我已经定义了 2 个 @Beans,每个 @Beans 具有唯一的名称,但具有相同的方法名称。没有创建 bean 之一,也没有抛出有效的 bean 异常。

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




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

第二个 Bean 没有被创建并且抛出异常,因为 ClassA 中没有有效的 bean。

This post 的两个 bean 在不同的类中,而在我的情况下,它们都在同一个 @Configuration 中。

【问题讨论】:

  • 一个class 不能有多个同名方法。你能展示你的代码和堆栈跟踪吗?
  • 你能提供堆栈跟踪吗?你如何注入这些豆子?

标签: java spring spring-boot spring-mvc javabeans


【解决方案1】:

当你通过bean name注入时,你可以使用@Resource

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

    // ...
}

顺便说一句,bean 应该以Java standard convention 命名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2020-09-06
    • 2023-04-01
    • 2020-03-24
    • 1970-01-01
    相关资源
    最近更新 更多