寻找使用内部 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}"
作为索引名称!
我也试过创建一个 @Component
叫 EsConfig
带字段 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/