SpringBoot ComponentScan与多模块项目有关 [英] SpringBoot ComponentScan issue with multi-module project
问题描述
我有一个带myapp-core和myapp-web模块的myapp父pom类型maven项目。 myapp-core模块作为依赖项添加到myapp-web。
I have a myapp parent pom type maven project with myapp-core and myapp-web modules. myapp-core module is added as dependency to myapp-web.
myapp-core模块中的所有类都位于root包 com.myapp.core 并且myapp-web模块中的所有类都位于root包 com.myapp.web
All the classes in myapp-core module reside in root package com.myapp.core and all classes in myapp-web module reside in root package com.myapp.web
主Application.java也在com中.myapp.web包。由于我的核心模块根包不同,我为ComponentScan包含了共同的基本包com.myapp,如下所示:
The main Application.java is also in com.myapp.web package. As my core module root package is different I am including common base package "com.myapp" for ComponentScan as follows:
@Configuration
@ComponentScan(basePackages="com.myapp")
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
现在令人惊讶的是,如果我使用此应用程序运行运行方式 - > Spring Boot App 它工作正常。但是,如果我将其作为运行方式 - > Java应用程序运行,则会失败并显示错误,说它无法在myapp-core模块中找到bean。
Now the surprising thing is if I run this app using Run As -> Spring Boot App it is working fine. But if I run it as Run As -> Java Application it is failing with error saying it can't found beans defined in myapp-core module.
如果我将 Application.java
移动到 com.myapp
包,它可以正常工作。
它应该工作,即使我也将它作为Java应用程序运行,对吗?
If I move my Application.java
to com.myapp
package it is working fine.
It should work even if i run it as Java Application also, right?
推荐答案
启用调试日志级别后我发现扫描各种组件(如JPA存储库,JPA实体等)取决于Application.java的包名称。
After enabling debug log level for spring and going through extensive logs I found that scanning for various components like JPA Repositories, JPA Entities etc are depending on the Application.java's package name.
如果是JPA存储库或实体不在 Application.java
的包的子包中,然后我们需要明确指定它们如下:
If the JPA Repositories or Entities are not in sub packages of Application.java
's package then we need to specify them explicitly as follows:
@Configuration
@ComponentScan(basePackages="com.sivalabs.jcart")
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages="com.sivalabs.jcart")
@EntityScan(basePackages="com.sivalabs.jcart")
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
使用上述额外的 @ EnableJpaRepositories
, @EntityScan
我可以使用运行方式 - > Java应用程序来运行它。
With the above additional @EnableJpaRepositories
, @EntityScan
I am able to run it using Run As -> Java Application.
但是当 Run As - > Spring Boot App !!
无论如何,我认为将 Application.java
移动到 com.myapp
包更好,而不是与SpringBoot打架!
Anyway I think it is better to move my Application.java
to com.myapp
package rather than fighting with SpringBoot!
这篇关于SpringBoot ComponentScan与多模块项目有关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!