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();
}
}
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:
Class where you want to autowire the template:
**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 beanuserTemplate
in the config class you can then autowire it into a field calleduserTemplate
without the@Qualifier
annotation