@Document indexName 中使用 Spring Data Elasticsearch 和 Spring Boot 的 SpEL 未被解析

2023-11-27

寻求使用内部 SpEL 的帮助@Document注释参考:

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

我在谷歌搜索上遇到了这个问题的帮助,因为关键字出现了不相关的问题(我已经看到了关于动态indexName的其他(未回答)问题).

我想设置

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

的值为indexName从属性派生(es.index-name)值写在我的application.properties.

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

我也尝试过创建一个@Component called EsConfig

有一个字段indexName注释为@Value("${es.index-name}")

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

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

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

这是完整的代码片段:

using @Document通过 SpEL 访问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;
  }
}

using @Document通过 SpEL 访问EsConfig indexName财产

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

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

@Document(indexName = "#{@esConfig.getIndexName()}")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

@Document indexName 中使用 Spring Data Elasticsearch 和 Spring Boot 的 SpEL 未被解析 的相关文章

随机推荐