问题描述
我有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);
}
}