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

问题描述

我有Spring Data Elaticsearch(使用Transport Client)和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
   }

}

我有一个配置,可以在其他项目中扩展上述配置。

@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;
    }
}

在执行第三个Spring Boot应用程序时,该应用程序使用ExtendedESConfig使用了对项目的依赖关系,我明白了这一点,我不太明白为什么会发生,并在升级到2.2.9之后开始发生。从2.0.5版本开始发布。发布Spring Boot版本。


***************************
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 - 

解决方法

在Spring Boot 2.1中已禁用了覆盖bean的默认行为。 Spring Boot 2.1 Release Notes

由于您不拥有/或不想修改两个配置类。您可以使用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);
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...