Spring Data Elasticsearch @Document indexName defined at runtime

浪尽此生 提交于 2019-11-29 00:06:19

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;
      }      

    }
  • Inject the value of configBean.getIndexName() into the "@Document" annotation using Spring EL : @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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!