java Spring Boot:配置类被简单地忽略而不加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41003355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:37:00  来源:igfitidea点击:

Spring Boot: Configuration Class is simply ignored and not loaded

javaspringspring-boot

提问by user991710

I have the following @Configurationclass on the classpath of a few of my @SpringBootApplications:

@Configuration的一些@SpringBootApplications的类路径上有以下类:

@Configuration
@Import({MainConfig.class, RestConfig.class})
public class ApiConfig {

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public Client client() throws ExecutionException, InterruptedException {
        return service.create(Client.class);
    }

}

I have two services that use this config (with differently named Clientclasses).

我有两个使用此配置的服务(具有不同命名的Client类)。

Service 1 starts correctly and loads this config. I can see during start up that a bean of type ApiConfigwas eagerly initialized.

服务 1 正确启动并加载此配置。我可以在启动期间看到一个类型的 beanApiConfig被急切地初始化。

Service 2 starts incorrectly: the above configuration class is simply ignored and not initialized.

服务 2 启动不正确:上面的配置类被简单地忽略并且没有初始化。

The services are started in separate JVMs.

这些服务在单独的 JVM 中启动。

Ther services have nearly identical, very small application.propertiesfiles:

这些服务具有几乎相同的非常小的application.properties文件:

spring.application.name=xxx-api
server.port=0
eureka.name=xxx.api
# Only for reading properties from a central location
context.initializer.classes=com.package.contextClass

I'm not even sure what kind of additional information I could write into the question. I have been going through logs for a couple of hours now and see no discernible difference, simply that it plainly ignores my @Configurationclass.

我什至不确定我可以在问题中写入什么样的附加信息。我已经浏览了几个小时的日志,并没有发现明显的区别,只是它显然忽略了我的@Configuration课程。

Has anyone had this issue before?

以前有人遇到过这个问题吗?

回答by Tom

The @SpringBootApplication annotation (or, more precisely the inferred @ComponentScan annotation) by default only scans the classpath next to and below the annotated class.

默认情况下,@SpringBootApplication 注释(或更准确地说是推断的 @ComponentScan 注释)仅扫描带注释的类旁边和下方的类路径。

So, your configuration class must be placed next to or in a sub package of you Application class.

因此,您的配置类必须放置在您的 Application 类的子包中或旁边。