跨 Java 包自动装配 Spring Bean

Cli*_*int 6 java spring spring-mvc spring-annotations

我试图将我的项目分成三个模块:核心、管理员和用户,以便我可以通过核心共享公共代码。问题是,当我将所有东西都放在同一个包中时,我无法让 Spring 在不同的主包中提取自动装配的 bean。

在 com.mickeycorp.core 包中,我有我希望管理和用户模块使用的模型、服务等。在 com.mickeycorp.admin 中是我的 WebApplicationStarter(扩展 SpringBootServletInitializer),我有:

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(SpringConfiguration.class);
    return application.sources(WebApplicationStarter.class);
}
Run Code Online (Sandbox Code Playgroud)

我认为应该选择我的配置类,其中包含以下内容:

@Configuration
@ComponentScan("com.mickeycorp")
public class SpringConfiguration {

}
Run Code Online (Sandbox Code Playgroud)

显然我误解了一些东西..我认为设置 ComponentScan 会使 Spring 扫描 com.mickeycorp 下的包以获取组件注释?

Cli*_*int 6

我是在正确的轨道上..添加@ComponentScan是只有三分之一的方式存在,是正确的,但它并没有配置Spring来扫描其它类型的-它只覆盖@Component @Repository@Service@Controller注解。我必须将以下内容添加到pickup@Entity@Repository

@EntityScan("com.mickeycorp.core")
@EnableJpaRepositories("com.mickeycorp.core")
Run Code Online (Sandbox Code Playgroud)

SpringApplicationBuilder在这种情况下也不需要覆盖,因为SpringConfiguration该类是自动选取的。

参考:

Spring 文档:实体扫描

Spring 文档:EnableJpaRepositories