ElasticSearch 索引名根据yml文件配置通过动态注解注入 EL表达式

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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值