总的来说,我对 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/