无法在SpEL中解析Spring Data MongoDB集合名称的bean

问题描述 投票:5回答:2

我正在尝试使用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)命名。

读取thisthis之后,创建了以下内容:

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 :(位置1):在上下文中未注册任何用于解析对bean'mongoCollections'的访问的bean解析器]

如果我使用这个:

@Document(collection = "#{mongoCollections.getCollectionFilesName()}")

例外是这个:

org.springframework.expression.spel.SpelEvaluationException:EL1007E :(位置0):属性或字段'mongoCollections'找不到null

最后,以下内容将使用指定的名称创建一个集合,包括符号:

@Document(collection = "@mongoCollections.getCollectionFilesName()")

我正在尝试使用Spring Data MongoDB和Spring Batch自定义将实体类保存到其中并建立索引的集合名称。该类的声明如下:@Document @CompoundIndex(...

spring-boot spring-batch spring-data-mongodb spring-el
2个回答
1
投票

this answer所指出的,以修复注入:

@Document(collection = "#{mongoCollections.getCollectionFilesName()}") 

0
投票

请确保您的bean mongoCollections已在应用程序上下文中注册,并按以下方式更正SpEL表达式。

© www.soinside.com 2019 - 2024. All rights reserved.