【发布时间】: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