我正在尝试使用 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
) 命名。看完this和 this ,我创建了以下内容:
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): No bean resolver registered in the context to resolve access to bean 'mongoCollections'
如果我使用这个:
@Document(collection = "#{mongoCollections.getCollectionFilesName()}")
异常(exception)是这个:
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'mongoCollections' cannot be found on null
最后,以下创建一个具有指定名称的集合,包括符号:
@Document(collection = "@mongoCollections.getCollectionFilesName()")
最佳答案
正如 this answer 所指出的那样, 修复注入(inject):
@Document(collection = "#{mongoCollections.getCollectionFilesName()}")
SpelEvaluationException: EL1007E:(pos 0): Property or field 'mongoCollections' cannot be found on null
(或直接方法 bean:
@Document(collection = "#{getCollectionFilesName}")
),尝试将 ApplicationContext 设置为 MongoMappingContext (用于实例化 MongoConverter,然后是 MongoTemplate):@Bean
public MongoMappingContext MongoMappingContext() {
MongoMappingContext mappingContext = new MongoMappingContext();
mappingContext.setApplicationContext(applicationContext);
return mappingContext;
}
关于spring-boot - 无法在 SpEL 中为 Spring Data MongoDB 集合名称解析 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41698445/