繁体   English   中英

Spring @ComponentScan在@Repository上不起作用

[英]Spring @ComponentScan doesn't work on @Repository

我有一个与配置类不同的包中的存储库,因此我用@Repostiory对其进行了如下注释:

package test;

@Repository
public interface UserTest extends JpaRepository<User, Long> {
}

我已经对其进行了组件扫描,但没有成功:

package com.app;
@SpringBootApplication
@ComponentScan({"test","com.app"})
public class Application extends SpringBootServletInitializer {
}

异常:没有类型为'test.UserTest'的合格Bean:至少应有1个有资格作为自动装配候选的Bean。

除非我添加enableJpaRepositories,否则组件扫描为什么不能在存储库上工作? 我以为componetScan就足够了


更新

由于一些答案提供了解决方案,我问的是解释而非解决方案。 即使不对“ test”进行组件扫描,也可以执行以下操作:

SpringBootApplication
@EnableJpaRepositories({"test","com.app"})
public class Application extends SpringBootServletInitializer{
}

现在的问题是,为什么当我无法使用@Repository时我什至需要使用componentscan? 为什么在文档中@Repository无效时组件可以扫描@Repository并且@EnableJpaRepostiories是enoguh?

来自Spring文档上有关组件扫描的内容:指示是否应启用对以@Component @ Repository,@ Service或@Controller注释的类的自动检测。

在我的情况下未检测到@Repository

为了让spring知道什么DataSource与哪个Repository相关,您应该在@EnableJpaRepositories批注中定义它。

尝试启用如下所示的jpa存储库。

@SpringBootApplication
@ComponentScan({"test","com.app"})
@EnableJpaRepositories("test")
public class Application extends SpringBootServletInitializer {
}

更新:为什么需要@EnableJpaRepositories?

@SpringBootApplication自动提供以下注释的功能

@Configuration @EnableAutoConfiguration @ComponentScan

但是,如果您尝试定义自己的注释,那么spring boot不会处理内部自动配置,因此这就是我们必须启用存储库的原因。

我有一些项目,如果您不编写自己的东西,仅使用@SpringBootApplication就足够了。

我希望你明白了。

黄金字:

如果您想最大程度地利用spring boot的自动配置功能,可以将所有类包都放在spring boot主应用程序包下(直接放在主包中或间接作为子包)。

我找到了关于我做错了事情的解释。 具有组件的@Repository批注不会导致spring实施spring jpa存储库。 对于实现Crud存储库的接口,应使用enablejparepository。

现在,将@Repository与componentscan一起使用是当您拥有一个存储库类并且您有自己的DAO 而不用于spring curd repo时,否则将不会创建实现:

@Repository
public class UserTest {


    public List<Object> findById(long l) {

             .......
    }
}

您应该像下面那样使用您的代码,因为@ComponentScan始终与基本软件包一起使用,因此您的实现应如下所示。

 package com.app;
    @SpringBootApplication
    @ComponentScan(basePackages={"test","com.app"})
    @EnableJPARepositories 
    public class Application extends SpringBootServletInitializer {
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM