spring-boot - 在@Document indexName中使用的SpEL与spring数据elasticsearch和spring boot没有被解析
问题描述
使用 SpEL inside 注释寻找一些帮助@Document
,参考:
spring-data-elasticsearch:3.2.3.RELEASE
和弹簧靴2.2.1 RELEASE
我在谷歌上搜索这个问题的帮助时遇到了麻烦,因为关键字选择了不相关的问题(我已经看到了关于动态 indexName 的另一个(未回答的)问题)。
我想设置
@Document(indexName = "${es.index-name}", ...)
使用从my 中写入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
属性
@Data
@Document(indexName = "#{esConfig.indexName}", type = "tests")
public class TestDocument {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String id;
}
解决方案
使用名称和方法引用您的 bean:
@Document(indexName = "#{@esConfig.getIndexName()}")
推荐阅读
- html - 如何在单一状态下处理多个选择框
- c - fgets 在 ac mini-sql 中显示“malloc():损坏的 top siz”
- swiftui - ScrollViewReader scrollTo 与 .center 锚错误?
- python - Sphinx 乳胶方程式警告:内联乳胶退出并出现错误 [stdout] 没有文件 math.aux
- javascript - 在前端 javascript 函数中使用 Scriptlet 代码
- discord - 如何在 discord.js 中停止循环
- javascript - TypeError: jquery__WEBPACK_IMPORTED_MODULE_7___default(...)(...).dropdown 不是函数 - reactjs 下拉菜单
- html - 我是 CSS 新手,如何改进此代码
- rust - 当 PartialOrd 更细微并返回 Option 时,为什么 PartialEq 返回一个布尔值
? - nosql - 用于数值字段的 DynamoDB GSI 与 LSI