我有一个工作的 Spring Boot Elasticsearch 应用程序,它使用两个配置文件之一:application.dev.properties 或 application.prod.properties。那部分工作正常。我在让外部 elasticsearch 从 application.xxx.properties 中读取时遇到问题。
这个有效:
@Configuration
@PropertySource(value = "classpath:config/elasticsearch.properties")
public class ElasticsearchConfiguration {
@Resource
private Environment environment;
@Bean
public Client client() {
TransportClient client = new TransportClient();
TransportAddress address = new InetSocketTransportAddress(
environment.getProperty("elasticsearch.host"),
Integer.parseInt(environment.getProperty("elasticsearch.port"))
);
client.addTransportAddress(address);
return client;
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(client());
}
}
但显然没有解决我的多环境问题。
我也尝试过对主机和端口变量使用@Value 注解,但没有成功。
我如何转换以上内容以从应用程序属性文件中读取其值或根据我要运行的配置文件选择不同的@PropertySource 文件?
spring.data.elasticsearch.properties.host = 10.10.1.10
spring.data.elasticsearch.properties.port = 9300
谢谢
最佳答案
删除您的配置类和属性。
添加如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
只需将 spring.data.elasticsearch
属性添加到 application-prod.properties
和 application-dev.properties
并更改所需的环境。这在 ElasticSearch section 中有描述。 Spring Boot 指南。
spring.data.elasticsearch.cluster-nodes=10.10.1.10:9300
这两个文件中的值当然会有所不同(或者将默认值放在 application.properties
中并简单地用 application-dev.properties
覆盖。
Spring Boot 将基于spring.profiles.active
load the desired properties文件。
没有必要绕过自己。
关于java - Spring Boot Elasticsearch 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32837507/