我的Service类中的spring-boot @autowired接口(CrudRepository)=>空指针异常

问题描述 投票:0回答:3

我有一些方法的公共接口

@Repository
public interface JobHistoryRepository extends CrudRepository<JobHistory, Long> {

    List<JobHistory> findByJobGroup(String jobGroup);
    JobHistory findById (Integer id);
    List<JobHistory> findByStateAndJobGroup(String state, String jobGroup);
    JobHistory findByJobNameAndJobGroupAndIdTrigger (String jobName, String jobGroup, String idTrigger);

}

我想在myclass服务中使用它

@Service
public class JobHistoryService {

    @Autowired
    private JobHistoryRepository jobHistoryRepository;


    public void setReadyJob(String jobId, String tenant, String idTrigger) {
    JobHistory jobHistory = new JobHistory();
     jobHistory.setJobName(jobId);
     jobHistory.setJobGroup(tenant);
     jobHistory.setIdTrigger(idTrigger);
     jobHistory.setIdUser("12345");
     jobHistory.setState("Ready");
     jobHistory.setDateCreation(new Date());

     jobHistoryRepository.save(jobHistory);   <--- at this point jobHistoryrespository is null why?
    }

编辑:我已经添加了@service@repository注释到我的课程,但这仍然无法正常工作。每次我使用JobHistory Service方法时,jobRepository依赖项仍为null。

如果我必须添加更多信息,请告诉我。谢谢。

java spring-boot jersey autowired
3个回答
0
投票

假设你有这样的接口:

public interface JobHistoryRepository extends CrudRepository<JobHistory, Long> {

    List<JobHistory> findByJobGroup(String jobGroup);
    JobHistory findById (Integer id);
    List<JobHistory> findByStateAndJobGroup(String state, String jobGroup);
    JobHistory findByJobNameAndJobGroupAndIdTrigger (String jobName, String jobGroup, String idTrigger);
}

然后创建一个服务类,如:

@Service
public class JobHistoryService {

    private final JobHistoryRepository jobHistoryRepository;

    public JobHistoryService (final JobHistoryRepository jobHistoryRepository)
    {
        this.jobHistoryRepository = jobHistoryRepository;
    }

    public void setReadyJob(String jobId, String tenant, String idTrigger) {
    JobHistory jobHistory = new JobHistory();
     jobHistory.setJobName(jobId);
     jobHistory.setJobGroup(tenant);
     jobHistory.setIdTrigger(idTrigger);
     jobHistory.setIdUser("12345");
     jobHistory.setState("Ready");
     jobHistory.setDateCreation(new Date());

     jobHistoryRepository.save(jobHistory);
    }

希望这可以帮助。


0
投票
JobHistoryService

应该也是一个Spring bean。注释它,例如与@Service

@Service
public class JobHistoryService {
...
}

0
投票

试试这个注释

@ComponentScan(basePackages = {"com.blabla.example.*"})

在Spring Boot Application Class上,检查您的存储库接口是否包含在该路径中。

我的例子:

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.blabla.gg.*"})
public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer{
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.