MongoDB and SpEL expressions in @Document annotations

I am trying to use SpEL to upload the same document to different collections based on specific rules that I defined.

So, to start with what I have:

- first of all, the document:

@Document(collection = "#{@mySpecialProvider.getTargetCollectionName()}")
public class MongoDocument {
// some random fields go in
}

-second I have a bean provider that should provide a collection name:

@Component("mySpecialProvider")
public class MySpecialProvider {

public String getTargetCollectionName() {
// Thread local magic goes in bellow
    String targetCollectionName = (String) RequestLocalContext.getFromLocalContext("targetCollectionName");
    if (targetCollectionName == null) {
        targetCollectionName = "defaultCollection";
    }
    return targetCollectionName;
 }
}

The problem is that when I try to insert a document into a specific collection that needs to be generated by the provider, I get the following stack:

org.springframework.expression.spel.SpelEvaluationException: EL1057E: (pos 1): no bean resolver registered in context to allow access to bean 'mySpecialProvider'

I also tried making the spring component ApplicationContextAware , but still no luck.

+1
2

, . , mongoTemplate bean XML :

<mongo:db-factory dbname="${myDatabaseName.from.properties.file}" mongo-ref="mongo"/>
<bean id="mongoMappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext"/>   
<bean id="mappingMongoConverter" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter" c:mongoDbFactory-ref="mongoDbFactory"
            c:mappingContext-ref="mongoMappingContext"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"
            c:mongoDbFactory-ref="mongoDbFactory" c:mongoConverter-ref="mappingMongoConverter"/>

, , . .

EDIT:

- , ThreadLocal:

RequestLocalContext, :

private static final ThreadLocal<Map> CONTEXT = new ThreadLocal<Map>() {
        protected Map initialValue() {
            Map localMap = new HashMap();
            localMap.put(LocalContextKeys.CONVERSATION_CONTEXT, new HashMap());
            return localMap;
        };
    };

public static void putInLocalContext(Object key, Object value) {
    Map localMap = CONTEXT.get();
    localMap.put(key, value);
}

 public static Object getFromLocalContext(Object key) {
    Map localMap = CONTEXT.get();
    return localMap.get(key);
}

LocalContextKeys - , , ThreadLocal . , , , .

+2

mongo: save (Object objectToSave, String collectionName).

0

All Articles