CommandLineRunner需要一个无法找到的bean

时间:2017-10-27 18:46:42

标签: 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> {
}

我缺少一个基本的东西吗? 提前致谢

2 个答案:

答案 0 :(得分:2)

最简单明智的事情

DemoApplication(或者使用sub connect_to_web Dim XMLPage As New MSXML2.XMLHTTP60 Dim url As String Dim query as string url="https://query1.finance.yahoo.com/v1/finance/screener?lang=en-US&region=US&formatted=true&corsDomain=finance.yahoo.com" XMLPage.Open "Post", url, False XMLPage.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" XMLPage.send "" Debug.Print XMLPage.Status XMLPage.send "" Debug.Print XMLPage.Status end sub 注释的任何类)应该位于包结构的根目录

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

换句话说,如果你的DemoApplication在一个包src / main / java / com / yourorg中,那么StudentRepository应该在src / main / java / com / yourorg

的(子)包中

答案 1 :(得分:1)

如果应用程序类不像其他类一样位于超级包中,则必须指定SpringBootApplication中应扫描的所有包(用于组件扫描,Spring Data存储库等)。

@SpringBootApplication(scanBasePackages= {"package1", "package2"})

或类型安全方法

@SpringBootApplication(scanBasePackageClasses = {ClassFromPackage1.class, ClassFromPackage2.class})

或者将所有包移动到应用程序类包的子包中,以便发生所有默认机制。