Is it possible to specify dynamically (at runtime) the indexName
for each @Document
, for example, via a configuration file? Or is it possible to make @Document
Spring environment (dev, prod) dependant?
Thank you!
Is it possible to specify dynamically (at runtime) the indexName
for each @Document
, for example, via a configuration file? Or is it possible to make @Document
Spring environment (dev, prod) dependant?
Thank you!
The @Document annotation does not permit to pass the indexname in parameter directly. However I found a work around.
In my configuration class I created a Bean returning a string. In this string I injected the name of the index with @Value :
@Value("${etrali.indexname}")
private String indexName;
@Bean
public String indexName(){
return indexName;
}
Afterward it is possible to inject the index into the @Documentation annotation like this :
@Document(indexName="#{@indexName}",type = "syslog_watcher")
It works for me, I hope it will help you.
Best regards
The solution from Bruno probably works but the "I created a Bean returning a string" part is a bit confusing.
Here is how I do it :
Have the "index.name" key valued in an application.properties file loaded by "<context:property-placeholder location="classpath:application.properties" />
"
Create a bean named ConfigBean annotated with @Named
or @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. : You may achieve the same result directly using the implicit bean "systemProperties" (something like #{ systemProperties['index.name'] }) but it didn't work for me and it's pretty hard to debug since u can't resolve systemProperties in a programmatic context (https://jira.spring.io/browse/SPR-6651)
The Bruno's solution works but there is no need to create a new Bean in this way. What I do is:
@org.springframework.stereotype.Service
where the index name is loaded from the database:@Service
public class ElasticsearchIndexConfigService {
private String elasticsearchIndexName;
// some code to update the elasticsearchIndexName variable
public String getIndexName() {
return elasticsearchIndexName;
}
}
@Document
annotation using the SpEL:@Document(indexName = "#{@elasticsearchIndexConfigService.getIndexName()}", createIndex = false)
public class MyEntity {
}
The crucial part is to use @
- #{elasticsearchIndexConfigService.getIndexName()}
won't work. I lost some time to figure this out.
This Worked for me
application.properties
index.prefix=test
then use this code
@Document(indexName = "#{@environment.getProperty('index.prefix')}")