Passing MongoTemplate to Custom Repository implementation

Viewed 7991

Project is configured to used multiple MongoTemplate s

Mongo Ref is passed as

@EnableMongoRepositories(basePackages={"com.mypackage.one"}, mongoTemplateRef="mongoTemplateOne")

for repositories in the package com.mypackage.one

and

@EnableMongoRepositories(basePackages={"com.mypackage.two"}, mongoTemplateRef="mongoTemplateTwo")

for repositories in the package com.mypackage.two

For standard repositories it works fine. But for the scenarios, where I need custom behavior, I define say myRepoCustomImpl with my custom behavior needs.

Problem: I need to have access to the MongoTemplate which the the analogous standard Repository.

e.g. If MyRepo is extending MyRepoCustom interface as

@Repository
interface MyRepo extends MongoRepository<MyEntity, String>, MyRepoCustom{}

MyRepoCustomImpl

@Service
    public class MyRepoCustomImpl implements MyRepoCustom{
        @Autowired
        @Qualifier("mongoTemplateOne")
        MongoTemplate mongoTmpl;

        @Override
        MyEntity myCustomNeedFunc(String arg){
            // MyImplemenation goes here
        }

}

If MyRepo is in package com.mypackage.one, the mongoTemplateOne will be used by myRepo, so there should be a some way to MyRepoCustomImpl will know that it should also use mongoTemplateOne, whenever I will make change in the mongoTemplateRef for MyRepo, say as

@EnableMongoRepositories(basePackages={"com.mypackage.one"}, mongoTemplateRef="mongoTemplateThree")

now I need to make changes to @Qualifier in the MyRepoCustomImpl! There are lots of repos with custom behaviour, so its becoming tedious task.

Question: Instead isn't there any way that the MongoTemplate to be used should get automatically injected or resolved according to the Repo it is extending to?

4 Answers
Related