Search code examples
javaspring-bootwebapp2component-scan

Spring @ComponentScan doesn't work on @Repository


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 {
}

Exception : No qualifying bean of type 'test.UserTest' available: expected at least 1 bean which qualifies as autowire candidate.

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


Update:

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{
}

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?

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

the @Repository in my case is not detected


Solution

  • 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.

    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) {
    
                 .......
        }
    }