Spring @ComponentScan 不适用于 @Repository [英] Spring @ComponentScan doesn't work on @Repository

查看:92
本文介绍了Spring @ComponentScan 不适用于 @Repository的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与配置类不同的包中有一个存储库,因此我使用@Repostiory 将其注释为以下内容:

I have a repository in different package than the configuration class , so I annotated it as the following with @Repostiory:

package test;

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

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

I have done the component scan on it and it didn't work :

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

异常:没有可用的test.UserTest"类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选.

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

why doesn't the component scan work on repository unless I add enableJpaRepositories ? I thought componetScan is enough

更新:

由于某些答案提供了解决方案,我问的是解释而不是解决方案.以下内容甚至无需对测试"进行组件扫描即可工作:

as some of the answers provides solution , I'm asking about explanation not solution . The following will work without even doing component scan on "test" :

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

现在的问题是为什么我什至需要在@Repository 上使用componentscan 不起作用?为什么在文档中@Repository 被componentscan 扫描时它没有效果并且@EnableJpaRepostiories 是enoguh?

Now the question why do I even need to use componentscan on @Repository when it doesn't work ? why in the documentation the @Repository is scanned by componentscan when it doesnt have effect and @EnableJpaRepostiories is enoguh?

来自关于组件扫描的 Spring 文档:指示是否应启用使用@Component @Repository、@Service 或@Controller 注释的类的自动检测.

from Spring documentation on component scan : Indicates whether automatic detection of classes annotated with @Component @Repository, @Service, or @Controller should be enabled.

没有检测到@Repository 在我的情况下

the @Repository in my case is not detected

推荐答案

我找到了关于我做错了什么的解释.带有componentscan的@Repository注解不会导致spring实现spring jpa仓库.对于实现 crud 存储库的接口,应使用 enablejparepository.

I found an explanation about what I was doing wrong. The @Repository annotation with componentscan will not cause spring to implement the spring jpa repository. for the interfaces that implement crud repository enablejparepository should be used.

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

Now the use of @Repository with componentscan is when you have a repository class and you have your own DAO not for spring curd repo otherwise the implementation won't be created :

@Repository
public class UserTest {


    public List<Object> findById(long l) {

             .......
    }
}

这篇关于Spring @ComponentScan 不适用于 @Repository的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆