【问题标题】:Error With Spring Boot Dependency Injection For Data Persistence用于数据持久性的 Spring Boot 依赖注入错误
【发布时间】:2021-12-26 06:45:57
【问题描述】:

我是 Spring Boot 的新手,但目前正在构建一个应用程序,该应用程序使用 Spring 不是为了它的 web 应用程序功能,而是利用它的数据源功能(使用 JPA 注释)。运行我的代码时,出现以下编译错误:


21-11-14 18:12:17.765 ERROR 13432 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskSerializableInteractor' defined in file [/Users/myname/softwarename/target/classes/api/TaskSerializableInteractor.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'taskSerializableRepository' defined in api.TaskSerializableRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class api.TaskSerializable

此错误向我表明 Spring Boot 在处理应用程序 API 类中定义的依赖注入时存在一些问题。项目本身相当大,我不知道这里调试需要哪些代码,但如果需要,我很乐意发布 sn-ps。我已经用谷歌搜索了几个小时,不知道如何解决这个问题。有关如何解决此错误的任何提示?

【问题讨论】:

  • 您能否展示一下TaskSerializable 类以及它是如何通过您的TaskSerializableRepository 引用的:)

标签: java spring database spring-boot jpa


【解决方案1】:

正如错误所说,您要注入的依赖项无法做到。这可能发生在以下情况:

  1. 没有匹配的构造函数。例如,如果你有这个类
//BAD PRACTICE
class Foo(){
    @Autowired
    private MyClass1 myClass1;
    @Autowired
    private MyClass2 myClass2;
    @Autowired
    private MyClass3 myClass3;

...
}

而且你没有定义任何构造函数,依赖没有被注入。这种情况下的正确做法:

class Foo(){
    private MyClass1 myClass1;
    private MyClass2 myClass2;
    private MyClass3 myClass3;

    @Autowired
    public Foo(MyClass1 myClass1, MyClass2 myClass2, MyClass3 myClass3){
        this.myClass1 = myClass1;
        this.myClass2 = myClass2;
        this.myClass3 = myClass3;
    }
}
  1. 您要注入的依赖项没有@Component,也没有定义@Bean 来注入它。您要注入的依赖项的名称和在 @Bean 上定义的方法应该是相等的。继续前面的例子:
@Configuration
public class MyBeanConfiguration(){

    @Bean
    public MyClass1 myClass1(){
        return new MyClass1(PARAMETERS)
    }

    ... SO ON ...
}

因此,请检查 classes/api/TaskSerializableInteractor 是否具有正确的构造函数以及是否定义了 bean 的配置。

如果你能展示部分课程,最好有更正确的想法。

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 2018-11-21
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    相关资源
    最近更新 更多