spring - CommandLineRunner 需要一个无法找到的 bean

标签 spring api

总的来说,我对 API 和 Spring 的开发还很陌生。

我正在尝试使用 CommandLineRunner 来填充我的存储库,但它说它找不到我放入参数中的所需 bean。

@SpringBootApplication
public class DemoApplication {

    private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);

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


    @Bean
    public CommandLineRunner initializeDB(StudentRepository studentRepository){
        return (args)->{
            studentRepository.save(new Student("John1", "Doe1", "asdasda1","Comp Sci1",21));
            studentRepository.save(new Student("John2", "Doe2", "asdasda2","Comp Sci2",22));
            studentRepository.save(new Student("John3", "Doe3", "asdasda3","Comp Sci3",23));
            studentRepository.save(new Student("John4", "Doe4", "asdasda4","Comp Sci4",24));
            studentRepository.save(new Student("John5", "Doe5", "asdasda5","Comp Sci5",25));
            studentRepository.save(new Student("John6", "Doe6", "asdasda6","Comp Sci6",26));
            logger.info("The sample data has been generated");
        };
    }
}

这是我的应用程序类,下面是我的存储库类。

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.model.Student;

public interface StudentRepository extends JpaRepository<Student, Integer> {
}

我缺少什么基本的东西吗? 提前致谢

最佳答案

最简单、明智的事情

DemoApplication(或用@SpringBootApplication注释的任何类)应驻留在包结构的根部

这意味着,对于您希望 spring 管理其 bean 生命周期的任何其他类,请将其移至 DemoApplication 的(子)包中。

换句话说,如果您的 DemoApplication 位于 src/main/java/com/yourorg 包中,那么 StudentRepository 应该位于 src/main/java/com/yourorg 的(子)包中

关于spring - CommandLineRunner 需要一个无法找到的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46981600/

相关文章:

javascript - 如何在不使用任何模型的情况下将多选值从 JSP 传递到 Controller

java - Spring Boot 和 Angular 身份验证 - 如何保护应用程序?

java - Spring 中的自定义异常处理/错误处理

javascript - NodeJs如何将变量传递给导出函数

java - Neo4j、REST API、java - 密码查询

android - 如何在android中使用Graph API获取喜欢我的Facebook帖子的人的数据

spring - JPA/JTA/@Transactional Spring 注解

Spring Boot JPA Like 查询

javascript - 如何使用 json 中的变量在 preload() 函数中调用另一个 json?

javascript - CRUD 后重新加载页面