Spring @ComponentScan doesn't work on @Repository

Mohammad Karmi picture Mohammad Karmi · Nov 6, 2018 · Viewed 7.2k times · Source

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

Answer

Alien picture Alien · Nov 6, 2018

In order to let spring knows what DataSource is related to what Repository you should define it at the @EnableJpaRepositories annotation.

Try enabling jpa repositories like below.

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

UPDATE : Why @EnableJpaRepositories needed?

@SpringBootApplication automatically provides the features of the following annotations

@Configuration @EnableAutoConfiguration @ComponentScan

But if you try defining your own annotation then spring boot will not take care of internal auto configurations so this is the reason we have to enable repositories.

I have projects in which only @SpringBootApplication is enough if you are not writing your own things.

I hope you got the point.

Golden words :

If you want to get the maximum advantage of spring boot’s auto configuration feature, it is expected to put all your class packages under spring boot main application package (directly in main package or indirectly as sub packages).