0

I am working spring data elastic search. Based on different header in the request, I create @RequestScope object IndexConfig to hold different set of indexes. It seems to be working. But I don't understand how singleton bean DocumentA/DocumentB can handle dynamic index? Do I need to set them @RequestScope as well?

@Component
@Data
@RequestScope
public class IndexConfig {

    private String AIndexName;
    private String BIndexName;
}

@Component
public class RequestFilter implements Filter {
    @Autowired
    private IndexConfig indexConfig ;
  
    public void doFilter(ServletRequest req,....) {
       
       if(httpRequest.getHeader("one"){
         indexConfig.setAIndexName("A1);
         indexConfig.setBIndexName("B1); 

      }else if(httpRequest.getHeader("two"){
         indexConfig.setAIndexName("A2);
         indexConfig.setBIndexName("B2); 
     }
    ..
    }
}  

@Document(indexName = "#{@indexConfig.getAIndexName()}", createIndex = false)
public class DocumentA {}

@Document(indexName = "#{@indexConfig.getBIndexName()}", createIndex = false)
public class DocumentB {}
Abe
  • 310
  • 3
  • 15

1 Answers1

1

What makes you think that DocumentA or DocumentB` are singletons? Thes e are the entities that you store and retrieve.

You create an instance of DocumentA and store it by either using methods of ElasticsearchOperations or using a respository function. And when retrieving data from Spring Data Elasticsearch, you get new instance(s) back, populated with the data that is read from Elasticsearch.

P.J.Meisch
  • 18,013
  • 6
  • 50
  • 66
  • Thank you @P.J.Meisch Another question..Can SpEL get the correct indexConfig bean? Is it thread safe in my code... indexName = "#{@indexConfig.getAIndexName()}" – Abe May 08 '22 at 21:53
  • it should give you then bean for the current request; thread-safety - probably not in a reactive environment – P.J.Meisch May 09 '22 at 17:13