首页 > 解决方案 > 无法在运行时设置 SolrDocument 注释

问题描述

我正在使用 Spring Data Solr,并且我有以下 Solr 文档模型类,并且该类具有相应的 SolrCrudRepository

@SolrDocument(collection = "oldCollectionName")
public class TestDocument {

            @Id
            @Indexed(name = "id", type = "string")
            private String id;

            @Field(value = "name")
            private String name;

            @Field(value = "externalid")
            private Integer externalId;
}

我正在尝试在运行时修改注释'@SolrDocument(collection = "oldCollectionName")'。

我有一个服务,它具有以下方法来使用存储库和模型类查找所有文档

public List<TestDocument> getDocumentsByName(String name){

        String newSolrDocument = getModifiedSolrCollectionName();
        alterAnnotationValue(TestDocument.class, SolrDocument.class, newSolrDocument);

        SolrDocument solrDocument = TestDocument.class.getAnnotation(SolrDocument.class);

        LOGGER.info("Dynamically set SolrDocument Annotaation: "+solrDocument.collection());

        return testDocumentRepository.findByName(name);
    }

更改注释的代码如下所示

   public void alterAnnotationValue(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
        try {
            Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null);
            method.setAccessible(true);

            Object annotationData = method.invoke(targetClass);

            Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS);
            annotations.setAccessible(true);

            Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
            map.put(targetAnnotation, targetValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

使用它我正确地将 newDocumentName 设置到注释映射中,但是在调用 testDocumentRepository 的 find 方法来查找文档时。旧的集合名称正在被选中。

我需要做更多的事情才能让它工作吗?或者我错过了什么?

作为参考,我遵循了以下教程http://www.baeldung.com/java-reflection-change-annotation-params

标签: javaspring-bootreflectionsolrspring-data-solr

解决方案


你为什么不写一个自定义SolrRepository来解决这个问题?您可以在自定义存储库中注入 a SolrTemplate,允许您为查询指定一个集合,如下所示:

public class TestDocumentRepositoryImpl implements TestDocumentRepository {

    private SolrOperations solrTemplate;
    ...
    public CustomSolrRepositoryImpl(SolrOperations solrTemplate) {
        super();
        this.solrTemplate = solrTemplate;
    }

    @Override
    public TestDocument findOneSpecifyingCollection(String collection, String id) {
        return solrTemplate.getById(collection, id, TestDocument.class);
    }
}

您可以对所需的存储库操作进行类似的操作。如果标准 Spring JPA 存储库不能满足他们的需求,人们通常需要他们自己的实现。但是,如果需要,您仍然可以将自己的标准与标准混合SolrCrudRepository

请参阅此以获取 Spring 的示例。


推荐阅读