spring boot mongo multiple database

2.1k views Asked by At

How can i configure application.properties to use multiple mongoTemplate

my current configuration.

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=user

My code:

public class UserRepository
{

     @Autowired
     private MongoTemplate mongoTemplate;

     public UserInfo getUserInfo(){
         //i can get user information from user database
         mongoTemplate.findAll();
     }
}

I want to get data from other database such as common database. For example

public class UserRepository
{

    @Autowired
    private MongoTemplate mongoUserTemplate;

    @Autowired
    private MongoTemplate mongoCommonTemplate;

    public UserInfo getUserInfo(){
        //i can get user information from user database
        mongoUserTemplate.findAll();

        //how can i configure application.properties to use 
        //mongoCommonTemplate...
        mongoCommonTemplate.findAll();
    }
}
1

There are 1 answers

0
robjwilkins On

There is a Qualifier annotation that you can use to provide a name for the bean you want to use.

So when you create the MongoTemplate objects give them different names. Then in the places where you want to use the different versions add a Qualifier annotation providing the name of the bean you want.

For example:

Config class:

@Configuration
public class AppConfig {

  public @Bean Mongo mongo() throws Exception {
      return new Mongo("localhost");
  }

  public @Bean MongoTemplate userTemplate() throws Exception {
      return new MongoTemplate(mongo(), "user");
  }
  public @Bean MongoTemplate commonTemplate() throws Exception {
      return new MongoTemplate(mongo(), "common");
  }
}

Class where you want to autowire the template:

@Autowired
@Qualifier("userTemplate")
private MongoTemplate userTemplate;
@Autowired
@Qualifier("commonTemplate")
private MongoTemplate commonTemplate;

**if the name of the bean matches the name of the field that you autowire it into, then I think you can even get away without using the Qualifier annotation. I.e. if you call the bean userTemplate in the config class you can then autowire it into a field called userTemplate without the @Qualifier annotation