我有使用Transport Client和ESTemplate的Spring Data Elasticsearch的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.0.5.RELEASE Spring Boot版本升级到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 -
我的评论中有一个重要的声明:
...很遗憾,我不是写这个ES配置并构建整个基础架构的人...
在提问时,我没有拥有ExtendedESConfig也无法更改它。
@Configuration
,且一个配置类继承另一个配置类。所以父类中的所有bean将被创建两次。请从父类中删除@Configuration
注解并尝试。此外,在配置类中使用继承不是一个好习惯。 - Pratapi Hemant PatelExtendedESConfig
类,则可以在@ComponentScan注释上使用excludeFilter来排除ESConfig
类。 - Pratapi Hemant Patel@Service
注释。这实际上也使它成为了@Bean
,而这与@Configuration
类中的@Bean
定义发生了冲突。在Spring 2.6.3中,删除@Service
修饰符解决了我的问题。 - Asa