在注释中使用 SpEL@Document
参考以下内容寻求帮助:
spring-data-elasticsearch:3.2.3.RELEASE
和弹簧靴2.2.1 RELEASE
我在谷歌上搜索这个问题时遇到了麻烦,因为关键字会选择不相关的问题(我已经看到了另一个关于动态 indexName 的(未回答的(问题(。
我想设置
@Document(indexName = "${es.index-name}", ...)
从我的application.properties
中写入的属性(es.index-name
(值派生的indexName
值。
而是使用文字字符串值"${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
(尝试使用和不使用龙目岛(
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;
}
用名称和方法引用你的 bean:
@Document(indexName = "#{@esConfig.getIndexName()}")