Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data MongoDB Repository with custom collection name

I am using Spring Data for MongoDB and I need to be able to configure collection at runtime.

My repository is defined as:

@Repository
public interface EventDataRepository extends MongoRepository<EventData, String> {
}

I tried this silly example:

@Document(collection = "${mongo.event.collection}")
public class EventData implements Serializable {

but mongo.event.collection did not resolve to a name as it does with a @Value annotation.

A bit more debugging and searching and I tried the following: @Document(collection = "#{${mongo.event.collection}}")

This produced an exception:

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)

Perhaps I just don't know how to quite use SPel to access values from Spring's Property Configurer.

When stepping through the code, I see that there is a way to specify collection name or even expressions, however, I am not sure which annotation should be used for this purpose or how to do it.

Thanks. -AP_

like image 819
Alex Paransky Avatar asked Apr 13 '15 03:04

Alex Paransky


1 Answers

So, at the end, here is a work around that did the trick. I guess I really don't know how to access data from Spring Properties Configurer using the SPeL expressions.

In my @Configuration class:

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

@Bean
public String mongoEventCollectionName() {
    return
        mongoEventCollectionName;
}

On my Document:

@Document(collection = "#{mongoEventCollectionName}")

This, appears to work and properly pick up the name configured in my .properties file, however, I am still not sure why I could not just access the value with $ as I do in the @Value annotation.

like image 52
Alex Paransky Avatar answered Nov 15 '22 01:11

Alex Paransky