ElasticSearch 索引名根据yml文件配置通过动态注解注入 EL表达式
背景
Java中的ES文档实体映射是通过注解 @Document 来实现,@Document 注解有两个参数:indexName 和 type。indexName 用于指定索引名称。
indexName是我们在编码的时候写死的,有个需求希望通过yml配置文档名,在不同的服务在不改变代码的前提下动态配置索引名称。
解决方案
查看Spring对接ES的源码SimpleElasticsearchPersistentEntity.java
,它可以通过EL表达式获取@Document 注解的indexName
private String getIndexName() {
if (indexName != null) {
// EL表达式解析
Expression expression = parser.parseExpression(indexName, ParserContext.TEMPLATE_EXPRESSION);
return expression.getValue(context, String.class);
}
return getTypeInformation().getType().getSimpleName();
}
在 yml 文件中定义索引名
elasticsearch:
index:
name: myindex
新增一个配置类获取索引名
@ConfigurationProperties(prefix = "revision")
@Component
@Getter
@Setter
public class IndexProperties {
private String indexName;
}
在实体类中使用:
@Document(indexName = "#{IndexProperties.indexName}", type = "customer")
public class Customer {
// properties and methods
}