外部 Jar 不工作 "Could not autowire"

External Jar not working "Could not autowire"

在 IntelliJ IDEA 中,我收到以下错误:

Could not autowire. No beans of 'ExternalClass' type found. Inspection info: Checks autowiring problems in a bean class

背景:我提取了一部分代码,并将其作为工件上传,当我尝试在我的 "main" 代码中使用它时出现错误,并且无法使用 maven 进行编译.

@Autowired
public ClassName (ExternalClass externalClass){
   this.externalClass = externalClass;
}

该工件是 POM 文件中的依赖项,它在自动完成时显示良好。

我试过几个类,每次都出现错误。

需要在提取的模块中定义一个@Configuration,并提供模块的扫描路径

@Configuration
// add any packages where you have bean definitions here (ex: ExtractedClass package)
@ComponentScan(basePackages = {"..."})
public class ExtractedConfig {

    // ...

}

然后,在你使用依赖的模块中,导入配置。

@Configuration
@Import(ExtractedConfig.class)
public class MainConfig {

    // ...

}

由于提取的 bean 在扫描路径中(因此符合自动装配条件),因此在重构之前您没有问题。当您将它们移动到不同的模块中时,情况就不再如此,您需要相应地调整扫描路径。

我最终发现了这个问题并正在分享以防其他人遇到同样的错误。 为了使 autowire 和 spring 正常工作,工件需要与主项目相同的包结构。 例子: 如果主项目包结构是:

com.domainname.something.myproject

神器应该是:

com.domainname.something.myproject.artifactname