Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't autowire repository from an external Jar into Spring Boot App

I have packaged my entire entities of the application and the repository interfaces into one jar. The repositories are written with @Repository annotation:

@Repository
public interface InternalUserRepository extends JpaRepository<InternalUser, Long>{

}

I have included this jar file inside my spring boot application and trying to autowire the interface like this from a controller:

@RestController
public class AuthenticationController {

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    InternalUserRepository internalUserRepository;


    @GetMapping("/")
    public String home() {
        return "Hello World!";
    }

}

My Main app class is written like:

@SpringBootApplication
@EnableJpaRepositories
@ComponentScan("com.cdac.dao.cdacdao.*")
public class CdacAuthenticationMgntApplication {

public static void main(String[] args) {
    SpringApplication.run(CdacAuthenticationMgntApplication.class, args);
}
}

The repository is not getting autowired. When I am firing up the Spring boor application I am getting the following error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field internalUserRepository in 
com.cdac.user.cdacauthenticationmgnt.controller.AuthenticationController required a bean of type 'com.cdac.dao.cdacdao.repository.InternalUserRepository' that could not be found.


Action:

Consider defining a bean of type 'com.cdac.dao.cdacdao.repository.InternalUserRepository' in your configuration.

Have anyone tried similar architecture like this?

like image 676
deDishari Avatar asked May 08 '18 10:05

deDishari


1 Answers

If your JPA repositories are in a different package than your Spring Boot application class, you have to specify that package on the EnableJpaRepositories annotation, not Component:

@EnableJpaRepositories("com.cdac.dao.cdacdao")

The package you specified on ComponentScan is for detecting classes as regular Spring beans, not repository interfaces.

like image 154
dunni Avatar answered Sep 21 '22 14:09

dunni