【问题标题】:strange behaviour with componentscan in spring bootspring boot中componentscan的奇怪行为
【发布时间】:2018-12-18 08:08:07
【问题描述】:

我有 3 个包裹:

  • 主包
  • 存储库
  • 控制器

在我的 SpringBootApplication 中我已经注释了:

@SpringBootApplication
@ComponentScan({"mainpackage","repositories","controller"})

在我的存储库包中,我有一个组件:

@Component
public interface UserRepository extends CrudRepository<User,Long> {
}

在我的控制器包中,我有一个自动装配“存储库”组件的控制器:

@RestController
public class MyController {

    @Autowired
    private UserRepository userRepository;

导致:

Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException

我做错了什么?

将所有类保存在一个包中是可行的,但我喜欢让它有点结构化。

【问题讨论】:

  • 将 UserRepository 更改为 @Repository
  • 同样的问题。 spring 容器找不到 bean(组件或存储库)。我不知道为什么?将 userRepository 移动到 mainpackage 时,它​​可以工作。

标签: spring components


【解决方案1】:

您正在使用 spring-data-jpa 存储库,但您的 SpringBootApplication 类中似乎没有任何 @EnableJpaRepositories

请添加,例如:

@SpringBootApplication
@ComponentScan({"mainpackage","repositories","controller"})
@EnableJpaRepositories("repositories")

您可能还需要在您的实体所在的包中添加@EntityScan

@EntityScan("entities")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-23
    • 2015-03-28
    • 2020-12-25
    • 2016-02-18
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多