1. With the MONGO of the previous article, we need more information, such as database name, username and password, to connect to the database.
We can continue to configure the instance of Mongodbfactory.
Public Interface mongodbfactory { throws DataAccessException; throws DataAccessException;}
Then we can continue to use mongodbfactory to create an instance of the mongotemplate.
Public classMongoapp {Private Static FinalLog log = Logfactory.getlog (Mongoapp.class); Public Static voidMain (string[] args)throwsException {mongooperations mongoops=NewMongotemplate (NewSimplemongodbfactory (NewMongo (), "database")); Mongoops.insert (NewPerson ("Joe", 34)); Log.info (Mongoops.findone (NewQuery (WHERE ("name"). Is ("Joe")), person.class)); Mongoops.dropcollection ("Person"); }}
One of the simplemongodbfactory is the realization of mongodbfactory.
2.1 Configuration via Java based metadata
@Configuration Public class mongoconfiguration { publicthrows Exception { returnNew simplemongodbfactory (new Mongo (), "Database");} }
If authentication is required, add one more parameter.
@Configuration Public classmongoconfiguration { Public@Bean mongodbfactory mongodbfactory ()throwsException {usercredentials usercredentials=NewUsercredentials ("Joe", "secret"); return NewSimplemongodbfactory (NewMongo (), "database", usercredentials); } Public@Bean mongotemplate mongotemplate ()throwsException {return Newmongotemplate (Mongodbfactory ()); }}
2.2 Configuring with XML
Simple usage (MONGO with default host and port number)
<mongo:db-factory dbname= "Database" >
Provides examples of host and port configuration
<id= "Anothermongodbfactory" host= "localhost" Port= "27017" dbname= "Database" username= "Joe" password= "secret"/>
If you need to configure more options, we can use Mongo-ref to point to an existing bean.
<Context:property-placeholder Location= "Classpath:/com/myapp/mongodb/config/mongo.properties"/><Mongo:mongoHost= "${mongo.host}"Port= "${mongo.port}"> <mongo:optionsConnections-per-host= "${mongo.connectionsperhost}"Threads-allowed-to-block-for-connection-multiplier= "${mongo.threadsallowedtoblockforconnectionmultiplier}"Connect-timeout= "${mongo.connecttimeout}"Max-wait-time= "${mongo.maxwaittime}"Auto-connect-retry= "${mongo.autoconnectretry}"socket-keep-alive= "${mongo.socketkeepalive}"Socket-timeout= "${mongo.sockettimeout}"Slave-ok= "${mongo.slaveok}"Write-number= "1"Write-timeout= "0"Write-fsync= "true"/></Mongo:mongo><mongo:db-factorydbname= "Database"Mongo-ref= "MONGO"/><BeanID= "Anothermongotemplate"class= "Org.springframework.data.mongodb.core.MongoTemplate"> <Constructor-argname= "Mongodbfactory"ref= "Mongodbfactory"/></Bean>