java - 无法在运行时设置 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
解决方案
你为什么不写一个自定义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 的示例。
推荐阅读
- regex - 缺少 html 标记属性时,正则表达式未捕获
- python - Tkinter 窗口打不开?
- string - 如何在 Flutter 中使用十六进制颜色字符串?
- c - 将字符串结尾字符添加到文件会损坏它..?
- python - Pandas - 如果列更大且不为空,则生成值
- javascript - .NET Core 2 端点不会在 POST 上为 FromBody 绑定参数
- java - 如何初始化变量以接受任何给定的类
- sed - 使用 sed 替换内容不同文件的文本
- c++ - wxWidgets,wxListCtrl:db-click 分隔线时如何防止自动调整列大小
- arrays - 有没有办法告诉 Rust 编译器在处理恐慌时对部分初始化的数组元素调用 drop ?