具有自定义集合名称的Spring Data MongoDB存储库

Ale*_*sky 5 java spring repository mongodb

我正在使用Spring Data for MongoDB,我需要能够在运行时配置集合.

我的存储库定义为:

@Repository
public interface EventDataRepository extends MongoRepository<EventData, String> {
}
Run Code Online (Sandbox Code Playgroud)

我试过这个愚蠢的例子:

@Document(collection = "${mongo.event.collection}")
public class EventData implements Serializable {
Run Code Online (Sandbox Code Playgroud)

但是mongo.event.collection没有像使用@Value注释那样解析为名称.

多一点调试和搜索,我尝试了以下内容:@Document(collection ="#{$ {mongo.event.collection}}")

这产生了一个例外:

Caused by: org.springframework.expression.spel.SpelParseException: EL1041E:(pos 1): After parsing a valid expression, there is still more data in the expression: 'lcurly({)'
    at org.springframework.expression.spel.standard.InternalSpelExpressionParser.doParseExpression(InternalSpelExpressionParser.java:129)
    at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:60)
    at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:32)
    at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpressions(TemplateAwareExpressionParser.java:154)
    at org.springframework.expression.common.TemplateAwareExpressionParser.parseTemplate(TemplateAwareExpressionParser.java:85)
Run Code Online (Sandbox Code Playgroud)

也许我只是不知道如何使用SPel来访问Spring的Property Configurer中的值.

单步执行代码时,我发现有一种方法可以指定集合名称甚至表达式,但是,我不确定应该将哪个注释用于此目的或如何执行.

谢谢.-AP_

Ale*_*sky 5

因此,最后,这是解决问题的方法。我想我真的不知道如何使用SPeL表达式从Spring Properties Configurer访问数据。

在我的@Configuration类中:

@Value("${mongo.event.collection}")
private String
    mongoEventCollectionName;

@Bean
public String mongoEventCollectionName() {
    return
        mongoEventCollectionName;
}
Run Code Online (Sandbox Code Playgroud)

在我的文件上:

@Document(collection = "#{mongoEventCollectionName}")
Run Code Online (Sandbox Code Playgroud)

这似乎可以正常工作,并且可以正确选择在.properties文件中配置的名称,但是,我仍然不确定为什么不能像在@Value批注中那样仅使用$访问值。


Oli*_*och 5

您只需使用 SPeL 即可解决此问题:

@Document(collection = "#{environment.getProperty('mongo.event.collection')}")
public class EventData implements Serializable {
    ...
}
Run Code Online (Sandbox Code Playgroud)

更新 Spring 5.x:

从 Spring 5.x 左右开始,您需要在环境之前添加一个 @ :

@Document(collection = "#{@environment.getProperty('mongo.event.collection')}")
public class EventData implements Serializable {
    ...
}
Run Code Online (Sandbox Code Playgroud)

文档: