【问题标题】:Could not autowire. No beans of type 'int' found无法自动接线。找不到“int”类型的 bean
【发布时间】:2018-07-30 08:48:21
【问题描述】:

我正在使用 Spring Boot,但在理解 Beans 时遇到了一些麻烦。我被引导相信 Beans 替换了 new 关键字。

我发现仅使用 Autowire 时,我的 Beans 不会在对象上创建新实例,并且我的 REST 应用程序将返回用户首先要求的相同响应(即,如果我最初访问 url/id/1,然后访问 url/id/2 REST 响应将与 url/id/1 相同)。

我试图通过创建一个@Configuration 文件来定义一个 bean 来解决这个问题。

@Configuration
public class UserConfig {

    @Autowired
    UserDAO DAO;

    @Bean
    public User getUser(int uid) {
        try {
            return DAO.getUser(uid);
        } catch (SIDException e) {
            return null;
        }
    }
}

但我在运行时不断收到此错误:Parameter 0 of method getUser in com.application.Config.UserConfig required a bean of type 'int' that could not be found.

我不明白这一点,因为我试图在配置文件中定义 Bean。

在我的主文件中,我有这些注释:

@SpringBootApplication(scanBasePackages = {"com.application.Config","com.application"})
@ComponentScan({"com.application.Config","com.application"})

如果有帮助,我会在这种情况下使用我的 bean:

@Service
public class UserService {

    @Autowired
    private UserDAO DAO;

    public User getUser(int uid) {
        try {
            return DAO.getUser(uid);
        } catch (SIDException e) {
            return null;
        }
    }
}

谢谢你:)

【问题讨论】:

  • 问题是因为你有一个 @Bean 注释,spring 会尝试选择它,期望 int 参数也是 Bean - 你没有语境。看起来只需用@Service 替换@Bean 就可以了。如果可行,我可以将其作为答案-但我手头没有环境来测试...

标签: java spring spring-boot


【解决方案1】:

@Bean 注释告诉 spring 运行方法来实例化某个对象。 Spring 需要创建参数 uid 来调用您的方法,但它不知道如何实例化 uid。所以:

  • 要么你的 int 是一个常量,所以让它成为 static final。
  • 要么你的 int 是一个配置,所以把它放到你的 application.properties 文件,并使用 @Value("${path.to.your.property.key}") 注入它。

【讨论】:

    【解决方案2】:

    当 Spring 尝试创建 bean 时,它需要知道 int uid 值。其他答案建议可能会解决该异常。

    但是您正在尝试做的是对 Spring 的不当使用。我建议您阅读有关春豆的信息,例如。 this , this 在继续之前。

    您的 getUser 方法不需要是 bean,您的 dao 是 bean,这就足够了。你的UserService 看起来不错,如果你对不同的 URL 得到相同的结果,你应该在 UserService.getUser 方法中调试 uid 值。如果那里的 uid 很好,那么在 Dao 中检查您的查询。

    【讨论】:

      猜你喜欢
      • 2021-01-17
      • 2019-08-17
      • 2021-07-02
      • 2020-08-31
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多