在服务层中注入自定义存储库实现

时间:2018-10-07 00:45:06

标签: java spring-boot spring-data-jpa

我编写了一个使用Spring JPA documentation作为参考的自定义JPA实现,并且希望将上述实现注入服务层,但是我无法弄清楚自己在做什么错。我也经历了following documentation as well。我的应用程序是Spring引导应用程序。

文档没有说明如何初始化我的自定义存储库实现。我试图遵循following instructions

我的服务层。

@Service
public class ProfileService implements IProfileService {

  @Autowired
  private IQuizRepository quizRepository;

  . . . . Some methods defined here. . . . 
}

我的JPA界面

@NoRepositoryBean
public interface IQuizRepository extends JpaRepository<Quiz, Long> {

  Quiz registerQuiz();

}

具体课程

public class QuizRepository extends SimpleJpaRepository<Quiz, Long> implements IQuizRepository {

 @PersistenceContext
 private EntityManager em;

 public QuizRepository(Class<Quiz> clazz, EntityManager em) {
   super(clazz, em);
 }

  /**
   * Initialises and returns a quiz attempt.
   */
  @Override     
  public Quiz registerQuiz() {
    String uniqueKey = UUID.randomUUID().toString().replaceAll("-", "");
    Quiz quiz = new Quiz();
    quiz.setQuizId(uniqueKey);
    Score score = new Score();
    quiz.setScore(score);
    score.setQuiz(quiz);
    this.save(quiz);
    return quiz;
  }

}

当我不使用QuizRepository注释Repository具体类时,就会出现以下错误。

***************************
APPLICATION FAILED TO START
***************************

Description:

Field quizRepository in com.myproject.service.ProfileService required a bean of type 'com.myproject.repository.IQuizRepository' that could not be found.


Action:

Consider defining a bean of type 'com.myproject.repository.IQuizRepository' in your configuration.

但是当我用QuizRepository注释@Repository时,出现以下错误

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.myproject.repository.QuizRepository required a bean of type 'java.lang.Class' that could not be found.


Action:

Consider defining a bean of type 'java.lang.Class' in your configuration.

我的项目结合了从JPA存储库继承的JPA接口和具体实现。

1 个答案:

答案 0 :(得分:0)

类似您的构造函数的声音需要具有这两个参数:

public QuizRepository(JpaEntityInformation<Quiz, Long> entityInformation, EntityManager entityManager) {
    super(entityInformation, entityManager);
    this.entityManager = entityManager;
}

代替public QuizRepository(Class<Quiz> clazz, EntityManager entityManager)