无法在SpringBoot项目中自动连接

时间:2017-02-28 15:41:45

标签: java spring-boot

所有节目都在这里。 https://github.com/horitaku1124/spring_batch_sample/tree/master/SpringBatchSample1

Main.java

public class Main {
    public static void main(String[] args) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        {
            JobLauncher jobLauncher = context.getBean("jobLauncher", JobLauncher.class);
            Job job = context.getBean("myJob1", Job.class);

            JobExecution execution = jobLauncher.run(job, new JobParameters());
            System.out.println("Job Exit Status : " + execution.getStatus());
        }
    }
}

MyBatchJob.java

public class MyBatchJob implements Tasklet {
    static Logger logger = Logger.getLogger("MyBatch");

    @PersistenceContext(type = PersistenceContextType.EXTENDED)
    private EntityManager entityManager;

    @Autowired
    private SampleTableRepository sampleTableRepo;

    public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
            throws Exception {
        SampleTableEntity sampleTable = new SampleTableEntity();
        sampleTable.setName("test name");
        sampleTable.setStatus(100);
        entityManager.persist(sampleTable);

        sampleTableRepo.findAll();

        System.out.println("Created SampleTableEntity=" + sampleTable.getId());
        return RepeatStatus.FINISHED;
    }
}

执行此Main.java,我收到此错误。

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.spring.repository.SampleTableRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

EntityManager效果很好。 但是在Autowired SampleTableRepository时我遇到了错误。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您应该在应用程序上下文中定义您的存储库,否则Spring无法找到它。