【问题标题】:SpEL used in @Document indexName with spring data elasticsearch and spring boot is not being parsed在@Document indexName中使用的SpEL与spring数据elasticsearch和spring boot没有被解析
【发布时间】:2020-04-04 06:53:22
【问题描述】:

使用 @Document 注释中的 SpEL 寻求一些帮助,参考:

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

我在谷歌上搜索这个问题的帮助时遇到了麻烦,因为关键字选择了不相关的问题(我见过other (unanswered) question about dynamic indexName)。

我想设置

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

indexName 的值源自我的application.properties 中写入的属性 (es.index-name) 值。

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

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

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

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

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

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

这里是完整的sn-ps代码:

使用 @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 属性

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 天哪,谢谢。这几天让我发疯了
    • 你知道为什么 "${es.index-name}" 和 "#{esConfig.indexName}" 都不起作用吗?
    • 索引名称参数使用需要#{...} 的 SpelExpressionParser 进行解析。在该表达式中,您需要使用 @ 引用 bean,并且您需要使用 getter 方法,而不是直接访问属性。你可以试试#{es.index-name} 但我不确定解析器是使用environemtn 还是只使用可用的bean。
    • 我明白了。让我感到困惑的是,我的朋友使用的是 spring boot 2.1.x + spring data elasticsearch 3.1.x,而对他来说 @Document(indexName = "#{esConfig.indexName}") 确实有效。我不明白为什么仅仅提升次要版本会有如此巨大的差异。更改日志中没有任何内容反映这一点。再次感谢您的帮助
    • 我花了几个月的时间尝试为不同的环境动态设置索引名称。感谢您的解决方案!
    猜你喜欢
    • 2016-01-09
    • 2019-04-22
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多