How can I change/define default database of Mongodb in Spring-data?
You just need to define respective mongobd properties in application.properties
file or if you want to yml syntax then define props in application.yml
. Under src/main/resources
, application.properties
should be there already.
application.properties
:
spring.data.mongodb.host=<hostname> spring.data.mongodb.port=27017 spring.data.mongodb.database=<dbname>spring.data.mongodb.username=<usernamr>spring.data.mongodb.password=******
Or
application.yml
:
spring: data: mongodb: host: <hostname> port: 27017 database: <dbname> username: <usernamr> password: ******
If you are using Spring Boot, the following steps might help you.
Define the following properties in application.properties or yml descriptor. note the properties should start with spring.data.mongodb. If you are using Mongo 3.x java driver, spring.data.mongodb.uri should be used to provide uri configurations.
spring.profiles: myprofilespring.data.mongodb.uri: mongodb://user:passwd@url:port/dbname spring.data.mongodb.database:myDB
Write SpringMongoConfiguration.
@Configuration@EnableMongoRepostories("path.to.your.repository")public class SpringMongoConfiguration extends AbstractMongoConfiguration {@Value("${spring.data.mongodb.uri}")private String mongoDB;@Value("${spring.data.mongodb.uri}")private String mongoURI;@Overrideprotected String getDatabaseName() { // TODO Auto-generated method stub return mongoDB;}@Overridepublic MongoMappingContext mongoMappingContext() throws ClassNotFoundException { // TODO Auto-generated method stub return super.mongoMappingContext();}@Override@Beanpublic Mongo mongo() throws Exception { return new MongoClient(new MongoClientURI(myURI));} }
Build your project and run your spring boot app
java -jar -Dspring.profiles.active=myprofile your-app.jar
If you are using context XML add the following in your XML and define the database configurations.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <mongo:mongo-client credentials="user:password@database" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongo" ref="mongo"/> <constructor-arg name="databaseName" value="myDBName"/> </bean></beans>
Alternatively, Define a class by extending AbstractMongoConfiguration and override the getDatabaseName().
@Configurationpublic class SpringDBConfig extends AbstractMongoConfiguration{ @Override protected String getDatabaseName() { return "testdatabase"; } ...... }