首页 > 解决方案 > 在@Document indexName中使用的SpEL与spring数据elasticsearch和spring boot没有被解析

问题描述

使用 SpEL inside 注释寻找一些帮助@Document,参考:

spring-data-elasticsearch:3.2.3.RELEASE和弹簧靴2.2.1 RELEASE

我在谷歌上搜索这个问题的帮助时遇到了麻烦,因为关键字选择了不相关的问题(我已经看到了关于动态 indexName 的另一个(未回答的)问题)。

我想设置

@Document(indexName = "${es.index-name}", ...)

使用从my 中写入indexName的属性 () 值派生的值。es.index-nameapplication.properties

而是使用文字字符串值"${es.index-name}"作为索引名称!

我也尝试过创建一个@Component被调用的EsConfig

带有indexName注释的字段@Value("${es.index-name}")

然后尝试使用 SpEL 访问此组件属性值:

@Document(indexName = "#{esConfig.indexName}", ...)

但这也不起作用(仍然解析为文字字符串并抱怨大写)。我已通过调试器确认该EsConfig组件正在正确解析 SpEL 并提供正确的值。但到达时失败@Document

以下是完整的代码片段:

使用@DocumentSpEL 访问application.properties

import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@Document(indexName = "${es.index-name}", type = "tests")
public class TestDocument {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id;
}

EsConfig data source Component(尝试使用和不使用 Lombok)

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("esConfig")
public class EsConfig {
  @Value("${es.index-name}")
  private String indexName;

  public String getIndexName() {
    return indexName;
  }

  public void setIndexName(String indexName) {
    this.indexName = indexName;
  }
}

使用@DocumentSpEL 访问EsConfig indexName属性

@Data
@Document(indexName = "#{esConfig.indexName}", type = "tests")
public class TestDocument {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id;
}

标签: spring-bootspring-annotationsspring-data-elasticsearchspring-el

解决方案


使用名称和方法引用您的 bean:

@Document(indexName = "#{@esConfig.getIndexName()}")

推荐阅读