spring积垢库-未满足的依赖关系表示-无法注入模型

oogrdqng  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(322)

我似乎无法让斯普林认出这个土著人 CrudRepository 使用它,因为spring不能注入/使用我的泛型 CrudRepository 当我把它放在一个与main方法不同的包中时需要实现。
我的项目结构非常简单。

像这样离开结构就行了!
但是我想 Author 呆在房间里 model 包裹,像这样:

然而,spring总是抛出错误:

Error creating bean with name 'demoApplication': Unsatisfied dependency expressed through field 'authorRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authorRepository' defined in service.AuthorRepository defined in @EnableJpaRepositories declared on DemoApplication: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class model.Author

我绝对不想通过application.properties.xml文件使用配置。我希望它在java代码中以编程方式配置。
这个 Author.java :

@Data
@NoArgsConstructor
@AllArgsConstructor

@Entity
@Table(name = "authors")
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(nullable = false)
    private String name;
}

这个 AuthorRepository 实现 CrudRepository :

@Repository
public interface AuthorRepository extends CrudRepository<Author, Integer> {
}

如果有什么重要的话,这里是 Config 我定义我的 DataSource . 这个 @BeanAuthor 似乎不重要,因为当我离开办公室时,没有它也能工作 Author 内部 com.example.demo 包裹。

@Configuration
public class Config {
    @Bean
    public DataSource dataSource(){
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url("jdbc:mysql://localhost:3306/sks");
        dataSourceBuilder.username("sks");
        dataSourceBuilder.password("technikum1");

        return dataSourceBuilder.build();
    }

    @Bean
    public Author author(){
        return new Author();
    }
}

最后是我的主要方法:

@SpringBootApplication
@ComponentScan(basePackages = {"config"})
@EnableJpaRepositories(basePackages = {"service"})
public class DemoApplication implements CommandLineRunner {

    @Autowired
    private AuthorRepository authorRepository;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    @Transactional
    public void run(String... args) throws Exception {
        Iterable<Author> authors = authorRepository.findAll();
        System.out.println(authors);
    }
}

我试着给 AuthorRepository 用一个 @ComponentScan(basePackages = {"model"}) 并注解了 Author.java@Component 因为我认为如果我把它放在另一个包中,它可能不会识别它是bean或其他什么东西(这无论如何都会很奇怪,因为当我把它放在主包中时我不需要组件注解),但是到目前为止什么都没用。总的来说,在项目结构和spring上苦苦挣扎。。。。
我也试着改变现状 @ComponentScan(basePackages = {"config"})DemoApplication@ComponentScan(basePackages = {"config","model"}) .
到目前为止什么都没用!
我需要帮助。。。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题