spring-boot - 在@Document indexName 中使用的 SpEL 与 spring 数据 elasticsearch 和 spring boot 没有被解析

标签 spring-boot spring-annotations spring-data-elasticsearch spring-el

寻找使用内部 SpEL 的一些帮助 @Document注释引用:
spring-data-elasticsearch:3.2.3.RELEASE和 Spring Boot 2.2.1 RELEASE
我在使用谷歌搜索帮助解决这个问题时遇到了麻烦,因为关键字会选择不相关的问题(我已经看到了 other (unanswered) question about dynamic indexName)。

我想设置
@Document(indexName = "${es.index-name}", ...)
indexName 的值派生自写在我的 es.index-name 中的属性 ( application.properties ) 值.

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

我也试过创建一个 @ComponentEsConfig
带字段 indexName@Value("${es.index-name}") 注释

然后尝试使用 SpEL 访问此组件属性值:
@Document(indexName = "#{esConfig.indexName}", ...)
但这也不起作用(仍然解析为文字字符串并提示大写)。我已经通过调试器确认 EsConfig组件正确解析 SpEL 并提供正确的值。但到达 @Document 时失败

以下是完整的代码片段:

使用 @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;
  }
}


使用 @Document使用 SpEL 访问 EsConfig indexName属性(property)

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

最佳答案

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

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

关于spring-boot - 在@Document indexName 中使用的 SpEL 与 spring 数据 elasticsearch 和 spring boot 没有被解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278195/

相关文章:

java - Elasticsearch java 客户端初始化失败

java - spring boot 和 elastic search 不支持版本最小兼容版本

elasticsearch - 将base64编码的字符串索引到ElasticSearch中的最佳方法

elasticsearch - 节点之一重新启动后,Elasticsearch中的未分配碎片

java - 对公共(public)和私有(private)资源使用不同的路径 Jersey + Spring boot

java - Spring Boot 抛出异常时不显示自定义错误

java - 如何将docker容器连接到远程数据库?

java - Spring Framework 中基于 Beans Java 的配置不起作用

java - Spring Security中PreAuthorize注解中使用permitAll()的目的