具有该名称的 bean 已在类路径资源 [path] 中定义并且覆盖被禁用

imp*_*ble 5 initialization exception spring-bean spring-boot spring-data-elasticsearch

我有 Spring Data Elaticsearch(使用传输客户端)和 ESTemplate 的 java 配置。这里有一些除外:

@Configuration
@EnableElasticsearchRepositories(basePackages = "subpackage-in-this-project")
@PropertySource("file:path-to-file")
public class ESConfig {

    @Bean
    ElasticsearchTemplate elasticsearchTemplate(Client client) {
        return new ElasticsearchTemplate(client);
    }

    @Bean
    Client client() { 
// configuration of the ES client
   }

}
Run Code Online (Sandbox Code Playgroud)

我有一个配置,可以在不同的项目中扩展上面的配置。

@Configuration
@ComponentScan("package-prefix-that-matches-packages-in-both-projects")
@EnableElasticsearchRepositories(basePackages = "subpackage-in-this-project")
@PropertySource("file:same-path-to-file-as-in-the-config-above")
public class ExtendedESConfig extends ESConfig {

    @Value("index-name")
    private String indexName;

    @Bean
    public String indexName() {
        return indexName;
    }
}
Run Code Online (Sandbox Code Playgroud)

在执行第三个 Spring Boot 应用程序时,它使用了对项目的依赖ExtendedESConfig,我得到了这个,我不太明白为什么会发生,从 2.0.5.RELEASE Spring 升级到 2.2.9.RELEASE 后开始发生引导版。


***************************
APPLICATION FAILED TO START
***************************

Description:

The bean 'elasticsearchTemplate', defined in class path resource [my/package/ESConfig.class], could not be registered. A bean with that name has already been defined in class path resource [my/other/package/ExtendedESConfig.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

2020-08-30 16:49:46 ERROR [main] org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter:40 - 
Run Code Online (Sandbox Code Playgroud)

IKo*_*IKo 17

或者您可以将下一个属性添加到您的application.properties

spring.main.allow-bean-definition-overriding=true
Run Code Online (Sandbox Code Playgroud)


Pra*_*tel 5

Spring Boot 2.1 中已禁用覆盖 bean 的默认行为。Spring Boot 2.1 发行说明

因为您不拥有/或不想修改这两个配置类。SpringBootApplication您可以使用以下命令从类中排除父配置@ComponentScan

@SpringBootApplication
@ComponentScan(excludeFilters = 
        {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = ESConfig.class)})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)