我已将应用程序的整个实体和存储库接口打包到一个jar中。存储库使用@Repository注释编写:
@Repository
public interface InternalUserRepository extends JpaRepository<InternalUser, Long>{
}
我已将此jar文件包含在我的spring启动应用程序中,并尝试从控制器自动装配这样的界面:
@RestController
public class AuthenticationController {
@Autowired
AuthenticationService authenticationService;
@Autowired
InternalUserRepository internalUserRepository;
@GetMapping("/")
public String home() {
return "Hello World!";
}
}
我的主应用程序类编写如下:
@SpringBootApplication
@EnableJpaRepositories
@ComponentScan("com.cdac.dao.cdacdao.*")
public class CdacAuthenticationMgntApplication {
public static void main(String[] args) {
SpringApplication.run(CdacAuthenticationMgntApplication.class, args);
}
}
存储库未获得自动装配。当我启动Spring boor应用程序时,我收到以下错误:
***************************
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.
是否有人尝试过这样的类似架构?
答案 0 :(得分:1)
如果您的JPA存储库与Spring Boot应用程序类位于不同的包中,则必须在EnableJpaRepositories
注释上指定该包,而不是Component
:
@EnableJpaRepositories("com.cdac.dao.cdacdao")
您在ComponentScan
上指定的包用于将类检测为常规Spring bean,而不是存储库接口。
答案 1 :(得分:0)
我记得,@ ComponentScan应该采用完整的包路径,所以我认为你的package.*
不起作用。
尝试使用类型安全的组件扫描:
// You refer to your packages of your base project and your module here.
// Choose the class so that their package is cover all child package
@SpringBootApplication(scanBasePackageClasses = {xxx. InternalUserRepository.class, xxx.CdacAuthenticationMgntApplication.class})
@EnableJpaRepositories
// No need to explicit @ComponentScan
public class CdacAuthenticationMgntApplication {
或者您可以尝试@EnableJpaRepositories("com.cdac.dao.cdacdao")
无论哪种方式,你应该在最外层的包中选择类(Spring也会尝试在这些组件扫描包的子包中找到bean)