【发布时间】:2019-08-06 04:49:54
【问题描述】:
我创建了一个小型 Spring Boot 项目,它将进行 DB 交互,我正在使用 @Controller、@Service 和 @Repository。
spring boot主类在父包com.bisnu.main下,那么controller、service和repository都在com.bisnu.main.service....这样的父包下。
一切都很好,但是当@Autowired 用于存储库时,它无法为存储库创建 bean,它给出了错误。
@EnableSwagger2
@RestController
@CrossOrigin(origins="*",allowedHeaders="*")
@RequestMapping("/TestController")
public class TestController {
@Autowired
private SourceService sourceService;
@GetMapping("/getSourcelist")
public List<SourceListDTO> getAllTelevisionSource(){
List<SourceListDTO> televisionSource = null;
televisionSource = sourceService.getTelevisionSource();
return televisionSource;
}
}
@Service
public class SourceService {
@Autowired
private TestRepository testRepo;
public List<SourceListDTO> getTelevisionSource() {
Pageable pageable = PageRequest.of(0, 100);
List<SourceListDTO> list = testRepo.findSourceList(pageable);
return list;
}
}
public interface TestRepository extends JpaRepository<MyTelevisionSource,Long> {
@Query("select query")
List<SourceListDTO> findSourceList(Pageable pageable);
}
我遇到了错误,
Field testRepo in com.tivo.extract.core.service.SourceService required a bean of type 'com.tivo.extract.core.repository.TestRepository' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.tivo.extract.core.repository.TestRepository' in your configuration.
谁能指导一下,这里出了什么问题。
谢谢
【问题讨论】:
-
@Repository 在存储库类中使用
-
我也试过了,同样的错误
-
请分享项目结构。应用程序级别的@ComponentScan 会这样做。但是如果包结构是正确的,那么它应该可以工作。
-
@dassum, 项目结构正确 com.bisnu.main --> 父com.bisnu.main.controller com.bisnu.main.repository com.bisnu.main.service
-
分享 @Query 。它实际上查询您使用的是哪个
标签: spring-boot spring-mvc autowired