【发布时间】:2017-06-01 14:14:37
【问题描述】:
我正在尝试使用 Spring Data MongoDB 和 Spring Batch 自定义实体类保存和索引的集合名称。该类声明如下:
@Document
@CompoundIndex(name = "unique_source", def = "{'fid': 1, 'sid': 1}", unique = true, background = true)
public class VariantSource {
...
}
还有项目作者:
public class VariantSourceMongoWriter extends MongoItemWriter<VariantSource> {
public VariantSourceEntityMongoWriter(MongoOperations mongoOperations, String collectionName) {
setTemplate(mongoOperations);
setCollection(collectionName);
}
}
保存工作正常:对象被写入作为参数提供的集合中。问题是索引是在默认集合中创建的,以类名 (variantSource) 命名。
public class MongoCollections {
public String getCollectionFilesName() {
return "my_custom_collection_name"; // TODO Dynamic value
}
}
@Configuration
public class MongoCollectionsConfiguration {
@Bean
public MongoCollections mongoCollections() {
return new MongoCollections();
}
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MongoCollectionsConfiguration.class})
public class VariantSourceMongoWriterTest {
@Autowired
private MongoCollections mongoCollections;
}
我已检查该实例是否正确自动装配到单元测试中,但我无法使其与 SpEL 一起使用。
将@Document 注释更改为如下所示:
@Document(collection = "#{@mongoCollections.getCollectionFilesName()}")
抛出以下异常:
org.springframework.expression.spel.SpelEvaluationException: EL1057E:(pos 1): 没有在上下文中注册 bean 解析器来解析对 bean 'mongoCollections' 的访问
如果我使用这个:
@Document(collection = "#{mongoCollections.getCollectionFilesName()}")
这个例外:
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): 在 null 上找不到属性或字段 'mongoCollections'
最后,下面创建了一个指定名称的集合,包括符号:
@Document(collection = "@mongoCollections.getCollectionFilesName()")
【问题讨论】:
-
感谢使用
@mongoCollections.getCollectionFilesName()的提示,这对我也有用!有谁知道为什么会这样?这甚至是有效的 SpEL 吗? -
@JanGassen
@mongoCollections.getCollectionFilesName()对我不起作用,它最终创建了一个名为@mongoCollections.getCollectionFilesName()的集合(非动态)。我正在使用 Spring Data 2.2.10。
标签: spring-boot spring-batch spring-data-mongodb spring-el