【发布时间】:2020-08-07 12:27:33
【问题描述】:
大家好
我有这个简化版的麻烦。我正在尝试运行我的应用程序,但它失败了,因为 Repository 未被识别为被注入。我已经尝试将存储库注释为服务并添加要扫描的存储库包,但没有一个有效。有人可以帮我吗?
我遇到了异常
说明:
br.com.alura.controller.TopicController 中的字段 topicRepository 需要一个找不到的“br.com.alura.repository.TopicRepository”类型的 bean。
注入点有以下注解: - @org.springframework.beans.factory.annotation.Autowired(required=true)
行动:
考虑在你的配置中定义一个“br.com.alura.repository.TopicRepository”类型的bean。
Controller/Service
@Autowired
private TopicRepository topicRepository;
@GetMapping(value = "/api/topics", produces = MediaType.APPLICATION_JSON_VALUE)
public Page<TopicBriefOutputDto> listTopics(TopicSearchInputDto topicSearch, @PageableDefault(sort="creationInstant", direction=Sort.Direction.DESC) Pageable pageRequest) {
Specification<Topic> topicSearchSpecification = topicSearch.build();
Page<Topic> topics = this.topicRepository.findAll(topicSearchSpecification, pageRequest);
return TopicBriefOutputDto.listFromTopics(topics);
}
Start
@SpringBootApplication
@Configuration
@ComponentScan(basePackages ={"br.com.alura.controller"})
@EntityScan
@EnableAutoConfiguration
@EnableJpaRepositories
@EnableSpringDataWebSupport
public class ForumApplication {
public static void main(String[] args) {
SpringApplication.run(ForumApplication.class, args);
}
}
Repository
public interface TopicRepository extends Repository<Topic, Long>, JpaSpecificationExecutor<Topic> {
}
【问题讨论】:
-
您不必显式添加 ComponentScan 注释。 SpringBootApplication 注解为您完成了这项工作。只需添加 basePackages = {"br.com.alura"}