Spring Boot JPA CrudRepository

2020-06-16 04:01发布

问题:

I'm working with Spring Boot + Spring Data JPA and facing this problem when trying to inject a class that extends CrudRepository:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'topicRepository': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

Repository Class:

public interface TopicRepository extends CrudRepository<Topic, Integer> {}

Service Class:

@Service
public class TopicService {

      @Autowired
      private TopicRepository topicRepository;
}

Any suggestions?

回答1:

I was having the same issue, and I fixed it by switching Spring Boot versions. Changing the Spring Data JPA versions did nothing (this is where I assumed the bug would be), so I think there is a bug in Spring Boot version 1.5.1. I switched back to version 1.4.3 and the error was gone. I didn't try subsequent/different versions, so you may just have to experiment with your dependencies and their versions.

For the record, you can have your service class annotated with @Repository, it shouldn't make any difference. I've been setting these apps up the same way using the service/dao pattern, and it has never been too picky with the annotations. Hopefully this may help others whose Spring Boot development flow suddenly throws an error!



回答2:

Which versions of spring-data-commons and spring-data-jpa are you using. I just ran into this using spring-data-commons 1.13.x with spring-data-jpa 1.10.x. Upgrading spring-data-jpa to 1.11.x fixed the issue for me.



回答3:

Make sure:

1) TopicRepository is annotated with @Repository.

2) You have the scanning packages configured:

<jpa:repositories base-package="mypkg.repositories"></jpa:repositories>


回答4:

I too had the same issue after updating Spring Boot to 1.5.4.

I am also using spring-data-envers, which was at version 1.0.4. Upgrading to 1.4.1 solved the problem.

I hope it helps someone :)



回答5:

Had the same issue on 1.5.2. Upgrading to 1.5.5 solved the problem.



回答6:

You can use Applicationcontext to inject repository to this reference topicRepository.. You just declare applicationcontext in @rest controller class Same like topicRepository by using annotation. Then you pass this to the service class which should take parms through constructor. Ex- public TopicService(Applicationcontext ctx) {this.topicRepository =context.getBean(TopicRepository.class); }