是否可以在运行时动态指定每个@Document
的indexName
,例如通过配置文件?或者是否可以使@Document
与Spring环境(开发、生产)相关联?
谢谢!
是否可以在运行时动态指定每个@Document
的indexName
,例如通过配置文件?或者是否可以使@Document
与Spring环境(开发、生产)相关联?
谢谢!
@Document注解不允许直接在参数中传递索引名称。不过我找到了一个解决方法。
在我的配置类中,我创建了一个返回字符串的Bean。在这个字符串中,我使用@Value注解注入了索引的名称:
@Value("${etrali.indexname}")
private String indexName;
@Bean
public String indexName(){
return indexName;
}
然后可以将索引注入到 @Documentation 注释中,如下所示:
@Document(indexName="#{@indexName}",type = "syslog_watcher")
对我来说有效,希望能帮到你。
最好的问候
Bean
?我是在带有 @Configuration
注解的 ElasticsearchConfig
类中进行的。但是,似乎我仍然遇到了 java.lang.NoClassDefFoundError
的问题。有什么建议吗? - nonNumericalFloat在一个由"<context:property-placeholder location="classpath:application.properties" />
"加载的application.properties文件中,将“index.name”键赋值
创建一个名为ConfigBean的Bean,并用@Named
或@Component
进行注释
@Named
public class ConfigBean {
@Value("${index.name}")
private String indexName;
public String getIndexName() {
return indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
}
@Document(indexName = "#{ configBean.indexName }", type = "myType")
P.S.:您可以直接使用隐式bean“systemProperties”来实现相同的结果(类似于#{ systemProperties['index.name']}),但对我来说它无法工作,而且很难调试,因为您无法在编程上下文中解析systemProperties (https://jira.spring.io/browse/SPR-6651)。
Bruno的解决方案可行,但是没有必要以这种方式创建一个新的Bean。我的做法是:
@org.springframework.stereotype.Service
注释的bean,在其中从数据库中加载索引名称:@Service
public class ElasticsearchIndexConfigService {
private String elasticsearchIndexName;
// some code to update the elasticsearchIndexName variable
public String getIndexName() {
return elasticsearchIndexName;
}
}
@Document
注释中的bean调用getIndexName()
方法:@Document(indexName = "#{@elasticsearchIndexConfigService.getIndexName()}", createIndex = false)
public class MyEntity {
}
@
- #{elasticsearchIndexConfigService.getIndexName()}
是无效的。我浪费了一些时间才弄清楚这一点。这对我有用
application.properties
index.prefix=test
然后使用这段代码
@Document(indexName = "#{@environment.getProperty('index.prefix')}")