【问题标题】:Repository Injection not been recognized as bean存储库注入未被识别为 bean
【发布时间】: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"}

标签: java spring


【解决方案1】:

可能您设置了不正确的base package。包范围太窄。

试试这个:

@EnableJpaRepositories(basePackages = {"br.com.alura.repository"})

或将br.com.alura.controller 更改为br.com.alura

@ComponentScan(basePackages ={"br.com.alura"})

【讨论】:

  • 我得到了一个新的异常 org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“topicController”的 bean 时出错:通过字段“topicRepository”表示不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.BeanCreationException:在 ForumApplication 上声明的 @EnableJpaRepositories 中定义的 br.com.alura.repository.TopicRepository 中创建名称为“topicRepository”的 bean 时出错:调用 init 方法失败;嵌套异常是 java.lang.IllegalArgumentException: Not a managed type: class br.com.alura.model.Topic
  • 主题用@Entity注释
  • 你到底做了什么?您可以尝试的另一个选项是@SpringBootApplication(scanBasePackages = "br.com.alura")
  • 我单独尝试过,也尝试过。但如果你看到那里,现在例外是实体,它在另一个包中
  • 添加@EntityScan(basePackages = "br.com.alura.model")
猜你喜欢
  • 1970-01-01
  • 2013-05-19
  • 2020-06-01
  • 2017-05-27
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多